Jersey / JAX-RS ExceptionMappers and Inheritance
I am using Jersey / JAX-RS to implement a RESTful web service. I have a question about an ExceptionMapper
interface that is not documented anywhere.
Let's say I have the following custom (extend RuntimeException
) exceptions:
-
FizzException extends RuntimeException
-
BuzzException extends FizzException
Now let's say that I want my exception handlers to do the following Exception
-to- mappings Response
:
-
FizzException
actually maps to HTTP 404 NOT FOUND -
BuzzException
maps to HTTP 403 UNAUTHORIZED - Anything else displays an HTTP 500 INTERNAL SERVER ERROR error
So, if I understood the API correctly, I need to implement 3 different Exception Mapping Agents:
@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, I am curious: since we have inheritance of the class of exceptions, which are actually being collected? For example:
-
BuzzException
extendsFizzException
, which ultimately extendsException
. So, if you select aBuzzException
, which will cause the display device:BuzzExceptionMapper
,FizzExceptionMapper
orDefaultExceptionMapper
? - Another way: when selected
Exception
, since aBuzzException
is ultimatelyException
which mapper: runsBuzzExceptionMapper
,FizzExceptionMapper
orDefaultExceptionMapper
?
+3
source to share