Converting Exceptions Into HTTP Status Codes

An exception thrown in an "exceptional" resource:

public class ExceptionalResource {

    public String dontCallMe() {
        throw new IllegalStateException("Do NOT call me");


can be easily converted into a HTTP Status code using the ExceptionMapper:


public class IllegalStateExceptionMapper 
implements ExceptionMapper<IllegalStateException> {

    public Response toResponse(IllegalStateException exception) {
        return Response.status(Response.Status.NOT_IMPLEMENTED).
                header("reason", exception.getMessage()).


A curl -i http://localhost:8080/jaxrs-exceptionmapper/resources/exceptions outputs:

reason: Do NOT call me
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!


wow, thanks bro.

Posted by kien tran on April 20, 2016 at 08:00 PM CEST #

It might be good to include status code in the output section.

Posted by Goran on April 21, 2016 at 09:02 AM CEST #

Mapping exceptions can be risky when applied generally, at least for Internet facing platforms, as it provides external parties with too much information about internal problems, e.g server ips, file paths, software / lib versions, dB connection strings, ...

Better to log it and tell your potential attacker little or nothing.

Posted by Chris on April 21, 2016 at 09:35 AM CEST #

Post a Comment:
  • HTML Syntax: NOT allowed
...the last 150 posts
...the last 10 comments