Exception Handling
JAX-RS resource methods and indeed the runtime may throw all kind of exceptions. JAX-RS WebApplicationException can be used to report an error from the application code or the custom JAX-RS providers. WebApplicationException can have the HTTP status, headers and error message included.
When the application code or provider throws the runtime or checked exception, what happens by default is that the uncaught exception is propagated up to the HTTP container level so that the existing exception-handling code in Servlet filters, if any, can deal with the exception. A JAX-RS ExceptionMapper implementation can be used instead to capture the exception and convert it into an appropriate HTTP response. For example, the following mapper catches a Spring Security exception and converts it into the HTTP 403 status:
package demo.jaxrs.server;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import org.springframework.security.access.AccessDeniedException;
public class SecurityExceptionMapper
implements ExceptionMapper<AccessDeniedException> {
public Response toResponse(AccessDeniedException exception) {
return Response.status(Response.Status.FORBIDDEN).build();
}
}