Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Write an ExceptionMapper that turns an OrderNotFoundException into a 404 response with a JSON problem body, and explain how JAX-RS picks a mapper when you also have an ExceptionMapper<RuntimeException>.

We write a @Provider class that implements ExceptionMapper<OrderNotFoundException>, and its toResponse returns Response.status(404).type("application/problem+json") with a problem body holding type, title, status, detail and instance. When an ExceptionMapper<RuntimeException> also exists, the runtime picks the mapper whose generic type is the nearest superclass of the thrown exception, so the specific mapper wins. A catch-all mapper for Throwable should log once with a correlation id and return a generic 500 without stack traces, and because mappers are singletons, request data must come from injected context proxies, not from fields we set.

Why this question is asked

Without exception mappers, an exception thrown from a resource becomes a bare 500 or a runtime-specific error page, and clients cannot tell a missing order from a crashed server. Mappers let us turn domain exceptions into clear HTTP responses in one place, so resource methods stay focused on the happy path. Interviewers ask this to see whether we can write a mapper correctly, produce a standard error body, and explain how the runtime chooses between mappers. In this answer, we will recap what an exception mapper is, write the 404 mapper with a problem details body, see how the runtime selects mappers by class distance, write a safe catch-all, and look at the lifecycle of mappers.

1A Quick Recap of Exception Mappers

In Jakarta REST, an exception mapper is a provider that converts an exception into an HTTP response. It implements ExceptionMapper<E> for some exception type E, has one method toResponse(E exception), and is registered like other providers with @Provider or explicit registration. When a resource method, or a filter, throws an exception, the runtime looks for a mapper for that exception type and sends whatever Response the mapper returns.

So resource methods can simply throw new OrderNotFoundException(42) when the order does not exist, and the decision about status code and body lives in one class that every resource shares.

2Writing the 404 Mapper

For the body, we use problem details, defined by RFC 9457 (which replaced RFC 7807): a small JSON object with the media type application/problem+json and standard fields. type is a URI identifying the kind of problem, title a short human summary, status the HTTP status, detail an explanation for this occurrence, and instance identifies this particular request or resource.

Java
public class OrderNotFoundException extends RuntimeException {
private final long orderId;
public OrderNotFoundException(long orderId) { super("order " + orderId); this.orderId = orderId; }
public long orderId() { return orderId; }
}
public record Problem(String type, String title, int status, String detail, String instance) {}
@Provider
public class OrderNotFoundMapper implements ExceptionMapper<OrderNotFoundException> {
@Context UriInfo uriInfo; // a per-request proxy, safe in a singleton
@Override
public Response toResponse(OrderNotFoundException e) {
Problem body = new Problem(
"https://api.example.com/problems/order-not-found",
"Order not found",
404,
"Order " + e.orderId() + " does not exist.",
uriInfo.getRequestUri().getPath());
return Response.status(Response.Status.NOT_FOUND)
.type("application/problem+json")
.entity(body)
.build();
}
}
// GET /orders/42 when order 42 is missing:
// 404, Content-Type: application/problem+json
// {"type":"https://api.example.com/problems/order-not-found","title":"Order not found",
// "status":404,"detail":"Order 42 does not exist.","instance":"/api/orders/42"}

Notice that the JSON provider must be willing to write the application/problem+json media type. Jackson's and JSON-B's JAX-RS providers generally accept types ending in +json, but if the body comes out empty or the request fails with a writer error, check your provider's supported media types.

3How the Runtime Chooses Between Mappers

Now suppose we also have ExceptionMapper<RuntimeException>. Both mappers could handle an OrderNotFoundException, because it is a RuntimeException. The specification resolves this by class distance: the runtime walks up from the thrown exception's class and picks the mapper whose generic type is the nearest superclass. OrderNotFoundException matches its own mapper at distance zero, while the RuntimeException mapper is one step further away, so the specific mapper wins.

An IllegalStateException, on the other hand, has no mapper of its own, so the nearest is RuntimeException at distance one, and that mapper handles it. The reason for this rule is the same as in Java's catch blocks: the most specific handler should apply.

Which mapper handles which exception
Thrown exceptionCandidate mappers (distance)Chosen
OrderNotFoundExceptionOrderNotFound (0), RuntimeException (1), Throwable (3)OrderNotFoundMapper
IllegalStateExceptionRuntimeException (1), Throwable (3)RuntimeException mapper
IOExceptionThrowable (2)Throwable mapper
The nearest superclass wins, just like the most specific catch block.

4A Safe Catch-all Mapper

For everything we did not foresee, a catch-all ExceptionMapper<Throwable> makes sure the client always gets the same problem format. It must do two things well: log the exception once, with its stack trace and a correlation id that also appears in the response, and return a generic 500 that reveals nothing about the internals, such as stack traces, SQL or class names.

Java
@Provider
public class UnexpectedErrorMapper implements ExceptionMapper<Throwable> {
private static final Logger log = LoggerFactory.getLogger(UnexpectedErrorMapper.class);
@Override
public Response toResponse(Throwable e) {
if (e instanceof WebApplicationException w) return w.getResponse(); // keep 404, 405, 409...
String id = UUID.randomUUID().toString();
log.error("Unexpected error, correlationId={}", id, e); // one log line with stack trace
Problem body = new Problem("about:blank", "Internal Server Error", 500,
"Something went wrong. Quote " + id + " when contacting support.", null);
return Response.serverError().type("application/problem+json").entity(body).build();
}
}

The first line matters more than it looks. A Throwable mapper also catches WebApplicationException and its subclasses, including the NotFoundException the runtime throws for unknown paths, and without that check every 404 would become a 500. In a real service, the correlation id would come from the trace context of the request rather than a new random value.

5Mappers Are Singletons

The runtime creates one instance of each provider and uses it for all requests at once. So we must never store per-request data in a mapper's fields, for example the current order id, because two requests would overwrite each other. Fields annotated @Context with standard types such as UriInfo or HttpHeaders are safe, because the runtime injects a proxy that looks up the current request's object on each call, but that is a feature of those context types, not of fields in general.

With CDI, constructor injection of services such as a metrics recorder works well and makes the dependency explicit. The mapper itself should stay small and fast, because it runs on the error path of every request.

6Follow-up questions

What happens if the mapper itself throws?

The specification says that if a mapper throws while creating the response, the runtime returns a 500 server error to the client, and it does not look for another mapper for the new exception. That prevents loops, but it means a bug in a mapper produces a bare 500 without our problem format, so mappers should be simple and tested.

Should OrderNotFoundException extend WebApplicationException instead?

It could, by passing a 404 Response to the super constructor, and then no mapper would be needed. But that ties a domain exception to JAX-RS. Keeping domain exceptions framework-free and mapping them at the edge keeps the service layer reusable.

How do you test a mapper?

Unit test toResponse with a sample exception and check the status, media type and body. Then add an integration test that calls GET /orders/999 through the running resources and checks the full 404 problem response.

7Conclusion

In this answer, we wrote an ExceptionMapper<OrderNotFoundException> that returns 404 with an application/problem+json body following RFC 9457. We saw that the runtime picks the mapper whose generic type is the nearest superclass of the thrown exception, so the specific mapper beats a RuntimeException mapper. A Throwable catch-all should pass WebApplicationException responses through, log once with a correlation id and return a generic 500, and because mappers are singletons, request data must not be kept in their fields.

What to say in the interviewAbout 90 seconds aloud

Open with

I would create a class annotated @Provider that implements ExceptionMapper of OrderNotFoundException. Its toResponse method builds a problem details body, as RFC 9457 defines: a type URI such as our problems/order-not-found page, a title like Order not found, status 404, a detail saying which order id is missing, and the instance, which I take from the injected UriInfo.

Then, if they want more

It returns Response.status(404).type("application/problem+json").entity(body).build(). Resource methods then just throw the domain exception. When there is also a mapper for RuntimeException, the runtime picks by class distance: it chooses the mapper whose generic type is the nearest superclass of the thrown exception.

OrderNotFoundException matches its own mapper exactly, so that one wins, and the RuntimeException mapper only handles runtime exceptions that have no closer mapper, like the most specific catch block in Java.

I would also have a catch-all mapper for Throwable, which logs the exception once with a correlation id and returns a generic 500 problem with that id but no stack trace or internal details. It has to pass WebApplicationException through by returning its response, otherwise it turns the runtime's 404s and 405s into 500s.

One more point: mappers are singletons, so I never keep request state in fields. @Context fields like UriInfo are fine because they are request-scoped proxies, and services come in through constructor injection with CDI.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Jakarta EE specifications
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Write an ExceptionMapper that turns an OrderNotFoundException into a 404 response with a...": https://scrivio-interview-library.netlify.app/java/jax-rs/31c6f898e1/