I currently have a REST service with JAX-RS in tomcat. Now I want the typical errors of 400,405,500 error, etc to be returned in JSON format and not HTML as it does in normal.
Then I've been basing myself on link to create an error handler.
This is a generic handler.
@Provider
public class GenericExceptionMapper implements ExceptionMapper<WebApplicationException> {
@Override
public Response toResponse(final WebApplicationException exception) {
final ErrorResponse response = new ErrorResponse("Generic excepton", "503",
"https://docs.oracle.com/javaee/7/api/javax/ws/rs/ext/ExceptionMapper.html");
return Response.ok().entity(response).build();
}
}
And this is a specific one (even if it's identical)
@Provider
public class NotAllowedExceptionMapper implements ExceptionMapper<NotAllowedException> {
@Override
public Response toResponse(final NotAllowedException exception) {
final ErrorResponse response = new ErrorResponse(exception.getMessage(), "503",
"https://docs.oracle.com/javaee/7/api/javax/ws/rs/ext/ExceptionMapper.html");
return Response.ok().entity(response).build();
}
}
Then I have already prepared to test it, so when you receive a request, automatically throw an exception.
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response list(@Context final UriInfo uriInfo, @Context final HttpHeaders httpHeaders,
@PathParam(USER_ID) final Integer userId, @QueryParam("offset") final Integer offset,
@QueryParam(LIMIT) final Integer limit, @PathParam(OPERATION_LABEL) final String oper) {
throw new NotAllowedException("test");
/*Response response;
if (oper.equalsIgnoreCase(RELOAD_OP)) {
response = reload();
} else {
response = listImplementation(uriInfo, httpHeaders, userId, offset, limit, oper);
}
return response;*/
}
Launched the following request
GET http://localhost:8080/webservice/persons
Putting a breaking point in WS waiting for the call I see that it reaches the throw new NotAllowedException("test");
but does not get to enter any of the two handlers that I have put and returns the classic html code.
<body><h1>Estado HTTP 405 – Method Not Allowed</h1><hr class="line" /><p><b>Tipo</b> Informe de estado</p><p><b>mensaje</b> Method Not Allowed</p><p><b>descripción</b> El método HTTP especificado no está permitido para el recurso requerido.</p><hr class="line" /><h3>Apache Tomcat/8.0.53</h3></body>
Any idea why I do not get into my handlers?