Converting Exceptions Into HTTP Status Codes 📎
@Path("exceptions")
public class ExceptionalResource {
@GET
public String dontCallMe() {
throw new IllegalStateException("Do NOT call me");
}
}
can be easily converted into a HTTP Status code using the ExceptionMapper:
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
@Provider
public class IllegalStateExceptionMapper
implements ExceptionMapper<IllegalStateException> {
@Override
public Response toResponse(IllegalStateException exception) {
return Response.status(Response.Status.NOT_IMPLEMENTED).
header("reason", exception.getMessage()).
build();
}
}
A curl -i http://localhost:8080/jaxrs-exceptionmapper/resources/exceptions
outputs:
reason: Do NOT call me
Content-Language:
Content-Type: text/html
Date: Wed, 20 Apr 2016 08:22:00 GMT
Connection: close
Content-Length: 1119
JPA OptimisticLockExceptions can be converted with the same mechanism.
Any questions left? See you at Java EE Workshops at Munich Airport, Terminal 2, particularly at: Effective Java EE 7 or at airhacks.io!