Enterprise Java
Handle custom exception types in JAX-RS
JAX-RS supports handling custom exceptions — thrown in either EJBs or CID beans — to custom HTTP responses.
Assuming we have an “exceptional” EJB:
01 02 03 04 05 06 07 08 09 10 11 | @Stateless public class Hello { public String greeting() { if ( new Random().nextBoolean()) throw new GreetingException( "Could not greet" ); return "hello" ; } } |
1 2 3 4 5 6 7 8 | @ApplicationException public class GreetingException extends RuntimeException { public GreetingException(String message) { super (message); } } |
The EJB is used in our JAX-RS resource:
01 02 03 04 05 06 07 08 09 10 11 12 | @Path ( "hello" ) public class HelloResource { @Inject Hello hello; @GET public String hello() { return hello.greeting(); } } |
Now to map the occurring exception to a custom HTTP response we can define a JAX-RS ExceptionMapper
.
01 02 03 04 05 06 07 08 09 10 11 | @Provider public class GreetingExceptionMapper implements ExceptionMapper<GreetingException> { @Override public Response toResponse(GreetingException exception) { return Response.status(Response.Status.CONFLICT) .header( "Conflict-Reason" , exception.getMessage()) .build(); } } |
The exception mapper is registered as a JAX-RS extension (by @Provider
) and will handle any GreetingException
thrown by a resource method.
The example will occasionally output HTTP 409 Conflict
with header Conflict-Reason: Could not greet
.
If a CDI managed bean is used instead of an EJB, the @ApplicationException
annotation is not required.
Published on Java Code Geeks with permission by Sebastian Daschner, partner at our JCG program. See the original article here: Handle custom exception types in JAX-RS Opinions expressed by Java Code Geeks contributors are their own. |