Goos van den Bekerom
Goos van den Bekerom

Reputation: 1493

Custom WebApplicationExceptions in jaxrs caught by ExceptionMapper show up in server log

I use the following Exceptionmapper to map WebApplicationExceptions in my jaxrs rest api to responses.

@Provider
public class ErrorHandler implements ExceptionMapper<WebApplicationException> {
    @Override
    public Response toResponse(WebApplicationException e) {
        int status = e.getResponse().getStatus();

        JsonObject errorResponse = Json.createObjectBuilder()
                .add("status", status)
                .add("message", e.getMessage())
                .build();

        return Response.status(status)
                .entity(errorResponse)
                .type(MediaType.APPLICATION_JSON)
                .build();
    }
}

This works fine and it does exactly what it should do, but when I throw custom errors, for example throw new NotFoundException("custom message"); the stacktrace shows up in my server log. Can anyone explain this? Or does anyone know of a solution?

TL;DR;

For some reason when I throw WebApplicationExceptions from my jax-rs code, my ExceptionMapper handles the error but still throws it so it shows up in the server log.

Any solutions?

Upvotes: 0

Views: 907

Answers (1)

Goos van den Bekerom
Goos van den Bekerom

Reputation: 1493

I've found the origin of this problem and managed to solve it.

From the JAX-RS spec

When choosing an exception mapping provider to map an exception, an implementation MUST use the provider whose generic type is the nearest superclass of the exception.

In my ExceptionMapper I used the WebApplicationException, so every error would be mapped. The problem is that WebApplicationException is not the nearest superclass of (e.g.) NotFoundException. There is a ClientErrorException superclass inbetween. When I changed my mapper to that class the problem was solved.

Since I only want to map client errors to Json responses this solution works fine for me.

Upvotes: 1

Related Questions