[ACCEPTED]-Custom HTTP status response with JAX-RS (Jersey) and @RolesAllowed-jsr250

Accepted answer
Score: 21

The easiest way to handle this sort of thing 14 is to throw an exception and to register 13 an exception mapper to convert into the 12 kind of message you want to send in that 11 case. So, suppose you throw an AccessDeniedException, you would 10 then have a handler like this (with full 9 class names in places for clarity):

public class AccessDeniedHandler
        implements javax.ws.rs.ext.ExceptionMapper<AccessDeniedException> {
    public javax.ws.rs.core.Response toResponse(AccessDeniedException exn) {
        // Construct+return the response here...
        return Response.status(403).type("text/plain")
                .entity("get lost, loser!").build();

The way 8 in which you register the exception mapper 7 varies according to the framework you're 6 using, but for Jersey you should be fine 5 with just using @Provider. I'll let you figure out 4 for yourself how you want to generate the 3 kind of error documents that you want, but 2 I do recommend handling failures as HTTP 1 error codes of some kind (that's more RESTful...)

Score: 9

With creating an ExceptionMapper (mapping exceptions of 4 WebApplicationException) it is possible to "catch" certain exceptions 3 thrown by the application:

public class MyExceptionMapper implements ExceptionMapper<WebApplicationException> {

    public Response toResponse(WebApplicationException weException) {

        // get initial response
        Response response = weException.getResponse();

        // create custom error
        MyError error = ...;

        // return the custom error
        return Response.status(response.getStatus()).entity(error).build();

You also need 2 to add the package to your application web.xml 1 for registering the provider:

        com.myapp.userservice; // semi-colon seperated
Score: 1

REST is build upon HTTP so you don't have 6 to change the default behavior of an authentication 5 failure. Having a 403 error when accessing 4 a resource is enough for the client to clearly 3 understand what appends.

The more your resources 2 are HTTP compliant, the more others can 1 understand it.

More Related questions