October 26, 2018

Exception Handling in JAX-RS 1.1 (EE 6)

ExceptionMapper

Exception/Error handling in JAX-RS is really good, you can write a custom error handler and registered it with @Provider.


import javax.json.Json;
import javax.json.JsonObject;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

@Provider
public class IllegalArgumentExceptionMapper implements ExceptionMapper {

    @Override
    public Response toResponse(IllegalArgumentException exception) {
        JsonObject body = Json.createObjectBuilder().add("title", exception.getMessage()).build();
        return Response.status(Response.Status.BAD_REQUEST).entity(body).build();
    }
}

Test


import javax.ws.rs.GET;
import javax.ws.rs.Path;

@Path("/person")
public class PersonResource {

    @GET
    public String hello() {
        throw new IllegalArgumentException("exception from hello");
    }
}

$ curl -i http://localhost:8080/example-javaee7/rest/person
HTTP/1.1 400 Bad Request
Connection: keep-alive
X-Powered-By: Undertow/1
Server: JBoss-EAP/7
Content-Type: application/json
Content-Length: 32
Date: Fri, 26 Oct 2018 17:09:16 GMT

{"title":"exception from hello"}

Standardizing REST Error

Different people write different error message, but there is a standard - Problem Details for HTTP APIs RFC 7807


3.1.  Members of a Problem Details Object

   A problem details object can have the following members:

   o  "type" (string) - A URI reference [RFC3986] that identifies the
      problem type.  This specification encourages that, when
      dereferenced, it provide human-readable documentation for the
      problem type (e.g., using HTML [W3C.REC-html5-20141028]).  When
      this member is not present, its value is assumed to be
      "about:blank".

   o  "title" (string) - A short, human-readable summary of the problem
      type.  It SHOULD NOT change from occurrence to occurrence of the
      problem, except for purposes of localization (e.g., using
      proactive content negotiation; see [RFC7231], Section 3.4).

   o  "status" (number) - The HTTP status code ([RFC7231], Section 6)
      generated by the origin server for this occurrence of the problem.

   o  "detail" (string) - A human-readable explanation specific to this
      occurrence of the problem.

   o  "instance" (string) - A URI reference that identifies the specific
      occurrence of the problem.  It may or may not yield further
      information if dereferenced.

For example:

   HTTP/1.1 400 Bad Request
   Content-Type: application/problem+json
   Content-Language: en

   {
   "type": "https://example.net/validation-error",
   "title": "Your request parameters didn't validate.",
   "invalid-params": [ {
                         "name": "age",
                         "reason": "must be a positive integer"
                       },
                       {
                         "name": "color",
                         "reason": "must be 'green', 'red' or 'blue'"}
                     ]
   }

Reference:

No comments: