How do I send an error response in Restlet?
Asked Answered
K

2

5

I have a Restlet ServerResource, which should process a GET request with a parameter user. If user is equal to some value, it should return some image, otherwise send an error response (404 or 403) indicating that the sender is not allowed to get the image.

import org.restlet.data.MediaType;
import org.restlet.representation.ObjectRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.Get;
import org.restlet.resource.ResourceException;
import org.restlet.resource.ServerResource;

public class GetMap extends ServerResource {
    @Get
    public Representation getImage() {
        final String user = getQuery().getValues("user");

        if (user.equals("me")) {
            //Read map from file and return it
            byte[] data = readImage();
            final ObjectRepresentation<byte[]> or=new ObjectRepresentation<byte[]>(data, MediaType.IMAGE_PNG) {
                @Override
                public void write(OutputStream os) throws IOException {
                    super.write(os);
                    os.write(this.getObject());
                }
            };
            return or;
        }
        return null; // Here I want to send an error response
    }
    [...]
}

How can I send a standardized error response in the getImage method (instead of return null) ?

Kop answered 25/11, 2015 at 8:36 Comment(0)
F
5

Have a look at the ServerResource#setStatus(Status) method JavaDoc and the additional overloaded methods. Which allows you to return a Custom body along with the desired HTTP Status.

Alternatively throw a new ResourceException (class JavaDoc) the framework will convert these to the correct HTTP status and provide a default message, although this is unlikely to be an image.

This should meet your needs. JavaDoc links to version 2.3.x on 25/11/2015

Fugazy answered 25/11, 2015 at 8:51 Comment(0)
M
4

In the past, I wrote a blog post about this:

In addition to the great Caleryn's answer, there is also now the @Status annotation to use custom exception within Restlet. A sample:

@Status(value = 400, serialize = true)
public class MyValidationException extends RuntimeException {
    public ServiceValidationException(String message, Exception e) {
        super(message, e);
    }
}

When such exception is thrown, Restlet automatically detects it and create the corresponding error message. In the sample, a response with the status code 400 and it tries to serialize the exception as a bean to JSON (or something else) using the converter service.

Hope it helps you, Thierry

Merman answered 25/11, 2015 at 19:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.