Exception handling with Restlet

Restlet provides several approaches to handle exceptions on both client and server sides. You can choose to be close to the Restlet API itself or use a higher level approach based on custom exceptions and / or annotated exceptions

On the server side

Restlet provides several approaches to handle exceptions on the server side. They correspond to different needs and allow to add flexibility when generating the corresponding response.

Basic approach for exceptions

Restlet allows to throw two kinds of exceptions within the annotated methods of server resources:

  • The exception ResourceException itself that corresponds to any exception that can occur within a server resource.
  • User-defined exceptions (both checked and unchecked exceptions). In the case of checked exceptions, we need to a throws in the method signatures. The Restlet engine will then catch them and wraps them within a ResourceException one.

That said, Restlet provides an indirection level to deduce the response status code and content when an exception is thrown within a server resource. As a matter of fact, the exception ResourceException is generic and only accepts to specify status code when creating it. A good approach is to implement user-defined exceptions describing the potential errors.

Then comes the status service of Restlet. The element is reponsible to create the response content when an exception is thrown. The default implementation returns description that comes along with a particular status code as text.

Restlet allows the service developer to override it and provide its own implementation.

Registering a custom status service can be simply done within the Restlet application class using the method setStatusService, as described below:

public class MyApplication extends Application {

    public MyApplication() {
        setStatusService(new MyCustomStatusService());

A custom status service needs to extend the class StatusService and override the following methods:

  • Method toStatus to determine the response status code from the thrown exception
  • Method toRepresentation to build the corresponding representation content

Following code describes the skeleton of a custom status service:

public class MyCustomStatusService extends StatusService {
    public Representation toRepresentation(Status status, Request request,
                               Response response) {
         Throwable t = status.getThrowable();
         Representation result = (...)
         return result;

    public Status toStatus(Throwable t, Request request,
                               Response response) {
        Status status = (...)
        return status;

We can notice that with version 2.3 of Restlet, overriden the method toStatus isnt required anymore since the status code associated to a user-defined exception can be defined in the exception class itself with an annotation.

Within the method toStatus, we simply need to check which exception was thrown and return the corresponding status code. Following code describes an implementation of this:

public Status toStatus(Throwable t, Request request,
                           Response response) {
    if (t instanceof MyValidationException) {
    } else if ((...)) {

Implementing the method toRepresentation can be a bit more complex. In fact we generally need to check if the client needs to receive back a structured representation or a user-friendly message (in HTML for example).

So we need first to implement an utility method that check this:

private boolean isHtmlContentRequested(Request request) {
    // Get accept media types for the client
    ClientInfo clientInfo = request.getClientInfo();
    List<Preference<MediaType>> mediaTypes
                        = clientInfo.getAcceptedMediaTypes();
    for (Preference<MediaType> mediaType : mediaTypes) {
        // Check if the media type is HTML
        if (MediaType.TEXT_HTML.equals(mediaType.getMetadata())) {
            return true;
    return false;

Based on this method, the skeleton of the method toRepresentation will be the following:

public Representation toRepresentation(
                 Status status, Request request, Response response) {
    // According to the preferred media type
    if (isHtmlContentRequested(request)) {
        // return HTML representation
        return toHtmlRepresentation(status, request, response);
    } else {
        // return structured representation of the error
        return toStructuredRepresentation(status, request, response);

We dont provide the content of the method toHtmlRepresentation since there are different ways to implement it (based on classes FileRepresentation or template engines, ). We will focus now on the implementation of the method toStructuredRepresentation that aims to define a data representation for errors.

This method will create a bean from the exception content and then leverage the converter service to convert this bean into a representation. The following snippet describes a sample implementation:

private Representation toStructuredRepresentation(
                   Status status, Request request, Response response) {
    Representation result = null;

    Throwable ex = status.getThrowable();
    Object o = getBeanFromException(ex);

    if (o != null) {
        List<org.restlet.engine.resource.VariantInfo> variants
                    = org.restlet.engine.converter.ConverterUtils
                                                   .getVariants(o.getClass(), null);
        if (!variants.contains(VARIANT_HTML)) {
        Variant variant = getConnegService().getPreferredVariant(
                                     variants, request, getMetadataService());
        try {
            result = getConverterService().toRepresentation(o, variant);
        } catch (IOException e) {
            throw new RuntimeException(e);
        return result;

    return super.toRepresentation(status, request, response);

Restlet also provides from its version 2.3 a way to manage error representations in a more flexible way without having to provide a custom status service.

Using annotated exceptions

Since the version 2.3, Restlet introduces the concept of annotated exceptions along with classical annotated interfaces of Restlet. This feature allows to serialize such user-defined exceptions as bean within the returned response for a particular

For example, if you want to map a request that returns a contact into a bean Contact. You can use something like that:

public interface MyService {
    Contact addContact(Contact contact);

You can use custom exceptions in this context and throws these, as described below:

public interface ContactResource {
    Contact addContact(Contact contact) throws MyValidationException;

This exception can use the annotation Status, as described below:

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

This exception can be thrown on the server side and serialized in the response as a bean (using its fields) thanks to the converter feature of Restlet. You can notice that we can add user fields to the custom exception.

For example, here, we could have a JSON content like this:

    "message": "my validation message"

Lets now tackle how to handle exceptions on the client side with Restlet.

On the client side

Like for the server side, we can use these two approaches to handle exceptions and errors on the client side with Restlet.

Basic approach

By default, Restlet throws an exception ResourceException when a status code other than 2xx is received in a response. We need to catch this exception to detect that an error occurs.

Whereas we dont have access to the representation returned by the call in such case, its nevertheless present in the response data and accessible using the method getResponseEntity of the class ClientResource.

The following snippet describes this:

ClientResource clientResource = (...)
JSONObject jsonObj = (...)
try {
    Representation representation = clientResource.post(
                                        new JsonRepresentation(jsonObj));
} catch (ResourceException ex) {
    Representation responseRepresentation
                           = clientResource.getResponseEntity();
    JsonRepresentation jsonRepr
                   = new JsonRepresentation(responseRepresentation);
    JSONObject errors = jsonRepr.getJsonObject();

We can notice that this approach can also be used along with annotated interfaces.

Catching annotated exceptions

On the client side, when the response is received, this custom exception will be thrown instead of a simple ResourceException and the content of the response (our JSON content for example) deserialized within the fields of the exception.

The following code describes how to use this approach on the client side along with the annotated interfaces one:

ClientResource cr = new ClientResource("http://...);
ContactResource contactResource = cr.wrap(ContactResource.class);
try {
    Contact newContact = new Contact();
    newContact.setName("my name");
    Contact addedContact = contactResource.addContact(newContact);
} catch(MyValidationException ex) {
    String errorMessage = ex.getMessage();

In your context, the code of the previous exception MyValidationException described above is reused.

This entry was posted in Restlet and tagged , , , , , . Bookmark the permalink.

2 Responses to Exception handling with Restlet

  1. shyam says:

    it is very good …. but a begineer in Restlet could not able to follow what is what.
    Hence could you please post complete sample (zip) .

    Thank you.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s