Error handling in REST API with JAX-RS Error handling in REST API with JAX-RS spring spring

Error handling in REST API with JAX-RS


When you have an ExceptionMapper, you don't catch the exception yourself, but have the framework catch it, when the resource method is invoked on an HTTP request.


The proper way to perform error handling is by registering ExceptionMapper instances that know what response should be returned in case of specific (or generic) exception.

@Providerpublic class PermissionExceptionHandler implements ExceptionMapper<PermissionException>{    @Override    public Response toResponse(PermissionException ex){        //You can place whatever logic you need here        return Response.status(403).entity(yourMessage).build();    }  }

Please take a look at my other answer for more details: https://stackoverflow.com/a/23858695/2588800


This is a Jersey example, but you can extract the needed informations from here. I would only throw an exception and map this exception to any wanted response in the end.

Lets assume you have following ressource method, thowing the exception:

@Path("items/{itemid}/")public Item getItem(@PathParam("itemid") String itemid) {  Item i = getItems().get(itemid);  if (i == null) {    throw new CustomNotFoundException("Item, " + itemid + ", is not found");  }  return i;}

Create your exception class:

public class CustomNotFoundException extends WebApplicationException {  /**  * Create a HTTP 404 (Not Found) exception.  */  public CustomNotFoundException() {    super(Responses.notFound().build());  }  /**  * Create a HTTP 404 (Not Found) exception.  * @param message the String that is the entity of the 404 response.  */  public CustomNotFoundException(String message) {    super(Response.status(Responses.NOT_FOUND).    entity(message).type("text/plain").build());  }}

Now add your exception mapper:

@Providerpublic class EntityNotFoundMapper implements ExceptionMapper<CustomNotFoundException> {  public Response toResponse(CustomNotFoundException  ex) {    return Response.status(404).      entity("Ouchhh, this item leads to following error:" + ex.getMessage()).      type("text/plain").      build();  }}

In the end you have to register your exception mapper, so it can be used in your application. Here is some pseudo-code:

register(new EntityNotFoundMapper());//orregister(EntityNotFoundMapper.class);