Thursday, July 7, 2016

JAX-RS Custom Exception Mapper

When the service(backend) throws any custom exception, using <javax.ws.rs.ext.ExceptionMapper> we can catch it , and send a relevant message to the client (/caller).

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

/**
 * Map the server exceptions to return to the client
 *
 */

@Provider
public class CustomJaxRsExceptionMapper implements ExceptionMapper {

@Override
     @Produces("application/json")
public Response toResponse(ServiceException e) {

          Map map = new HashMap();
  map.put("Exception", e.getMessage());

Response response = Response.status(500).entity(map).build();
return response;
}
}

No comments:

Post a Comment