IAmYourFaja
IAmYourFaja

Reputation: 56914

Jersey/JAX-RS ExceptionMappers and Inheritance

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:

Now let's say that I want my exception mappers to perform the following Exception-to-Response mappings:

So, 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:

Upvotes: 3

Views: 951

Answers (1)

Vinayak
Vinayak

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
  • others Exception will be mapped by DefaultExceptionMapper

Upvotes: 5

Related Questions