I have two classes that implements ExceptionMapper
interface.
IllegalArgumentExceptionMapper
to handle IllegalArgumentException
:
@Slf4j
@Provider
public class IllegalArgumentExceptionMapper implements ExceptionMapper<IllegalArgumentException> {
@Override
public Response toResponse(IllegalArgumentException exception) {
log.info("IllegalArgumentExceptionMapper!");
Error error =
Error.builder()
.statusCode(HttpStatus.SC_BAD_REQUEST)
.statusDescription(exception.getLocalizedMessage())
.errorMessage(exception.getMessage())
.build();
return Response.status(Response.Status.BAD_REQUEST)
.entity(error)
.type(MediaType.APPLICATION_JSON)
.build();
}
}
GenericExceptionMapper
is an ExceptionMapper that I want to use as the default ExceptionMapper when an exception is not mapped to any of my other specific ExceptionMapper classes. Here it is:
@Slf4j
@Provider
public class GenericExceptionMapper implements ExceptionMapper<Throwable> {
@Override
public Response toResponse(Throwable ex) {
log.info("GenericExceptionMapper!");
Response.StatusType type = getStatusType(ex);
Error error = Error.builder()
.statusCode(type.getStatusCode())
.statusDescription(type.getReasonPhrase())
.errorMessage(ex.getLocalizedMessage())
.build();
return Response.status(error.getStatusCode())
.entity(error)
.type(MediaType.APPLICATION_JSON)
.build();
}
private Response.StatusType getStatusType(Throwable ex) {
if (ex instanceof WebApplicationException) {
return((WebApplicationException)ex).getResponse().getStatusInfo();
} else {
return Response.Status.INTERNAL_SERVER_ERROR;
}
}
}
However, when I try to throw an IllegalArgumentException
, with:
throw new IllegalArgumentException("Just a normal IllegalArgumentException!");
I see that GenericExceptionMapper
instead of IllegalArgumentExceptionMapper
is being used.(I see "GenericExceptionMapper!" in the log).
Any idea what went wrong?
Some observations
- If I delete
GenericExceptionMapper
,IllegalArgumentExceptionMapper
is still not being called. So I think there is an issue for myIllegalArgumentExceptionMapper
implementation. - If I modify
IllegalArgumentExceptionMapper
withpublic class IllegalArgumentExceptionMapper implements ExceptionMapper<RuntimeException>
andthrow new RuntimeException
, then I see thatIllegalArgumentExceptionMapper
is being used.