简体   繁体   中英

Restlet error response format in JSON

Im using the restlet framework to manager a projects API. It seems that by default error responses are formatted in HTML. How can I change that so that by default ALL error responses are in JSON format?

I've tried adding a custom converter which works great for the entity responses but not for error responses.

We have 110+ endpoints that support application/json so ideally I would like to just set the default errors to always return as JSON. The default converter works for all methods that return an actual entity.

@Get("json")
@Produces("application/json")
public User represent() {
    ...
    return result;
}

But the ResourceException thrown by this method returns HTML.

If you are sure about the format your service is going to produce then you can annotate your service class with @Produces annotation at class level. Then you will not be required to define the same for each and every method.

Also, once @Produces is defined at class level and you want to change response format for a particular method then you can annotate that particular method for other format.

Try Below code..

public Response represent(){
try{

}catch(Exception ex){
    return Response.status(500)
            .entity(new ExceptionMessage("500", ex.getMessage()))
            .type(MediaType.APPLICATION_JSON).
            build();
}
return Response.status(Response.Status.OK).entity(result).build();

}

And have below Model class for exception message.

@XmlRootElement
class ExceptionMessage{
    private String statusCode;
    private String errorMessage;

    public ExceptionMessage() {
    }

    public ExceptionMessage(String statusCode, String errorMessage) {
        this.statusCode = statusCode;
        this.errorMessage = errorMessage;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }

    public String getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(String statusCode) {
        this.statusCode = statusCode;
    }

}

This is the link dedicated to Restlet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM