[ACCEPTED]-Custom HTTP status response with JAX-RS (Jersey) and @RolesAllowed-jsr250
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):
@javax.ws.rs.ext.Provider
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...)
With creating an ExceptionMapper
(mapping exceptions of 4 WebApplicationException
) it is possible to "catch" certain exceptions 3 thrown by the application:
@Provider
public class MyExceptionMapper implements ExceptionMapper<WebApplicationException> {
@Override
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:
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>
com.myapp.userservice; // semi-colon seperated
com.myapp.mappedexception
</param-value>
</init-param>
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
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.