Converting Exceptions Into HTTP Status Codes

An exception thrown in an "exceptional" resource:


@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!

Comments:

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
License