Reputation: 56914
I'm using Jersey/JAX-RS to implement a RESTful web service. I have a question about the ExceptionMapper
interface, which doesn't appear to be documented anywhere.
Say I have the following custom (extend RuntimeException
) exceptions:
FizzException extends RuntimeException
BuzzException extends FizzException
Now let's say that I want my exception mappers to perform the following Exception
-to-Response
mappings:
FizzException
actually maps to an HTTP 404 NOT FOUNDBuzzException
maps to an HTTP 403 UNAUTHORIZEDSo, if I understand the API correctly, I need to implement 3 different exception mappers:
@Provider
public class DefaultExceptionMapper implements ExceptionMapper<Exception> {
@Override
Response toResponse(Exception exc) {
// Map to HTTP 500
}
}
@Provider
public class FizzExceptionMapper implements ExceptionMapper<FizzException> {
@Override
Response toResponse(Exception exc) {
// Map to HTTP 404
}
}
@Provider
public class BuzzExceptionMapper implements ExceptionMapper<BuzzException> {
@Override
Response toResponse(Exception exc) {
// Map to HTTP 403
}
}
However, this has me curious: since we have exception class inheritance going on, which mappers will actually fire? For instance:
BuzzException
extends FizzException
, which ultimately extends Exception
. So, if a BuzzException
is thrown, which mapper will fire: BuzzExceptionMapper
, FizzExceptionMapper
or DefaultExceptionMapper
?Exception
is thrown, since a BuzzException
is, ultimately, an Exception
, which mapper fires: BuzzExceptionMapper
, FizzExceptionMapper
or DefaultExceptionMapper
?Upvotes: 3
Views: 951
Reputation: 96
Most specific exception mapper will be called.
So in your case :
BuzzException
will be mapped by BuzzExceptionMapper
FizzException
will be mapped by FizzExceptionMapper
Exception
will be mapped by DefaultExceptionMapper
Upvotes: 5