Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I send an error response in Restlet?

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) ?

like image 610
Dmitrii Pisarenko Avatar asked Nov 25 '15 08:11

Dmitrii Pisarenko


2 Answers

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

like image 105
Caleryn Avatar answered Nov 20 '22 06:11

Caleryn


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

  • Exception handling with Restlet: https://templth.wordpress.com/2015/02/27/exception-handling-with-restlet/

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

like image 39
Thierry Templier Avatar answered Nov 20 '22 07:11

Thierry Templier