Scrivio Interview library
DebuggingIntermediate6 min read · updated 12 November 2026

A resource throws new WebApplicationException(Response.status(409).entity(body).build()), but clients receive a 500 with a generic error from your ExceptionMapper<Throwable>. In another case, NotFoundException thrown by the runtime for unknown paths is also turned into 500. Explain and fix.

An ExceptionMapper<Throwable> also matches WebApplicationException and all its subclasses, including the NotFoundException, NotAllowedException and NotSupportedException that the runtime itself throws for unknown paths, wrong methods and wrong media types, so the catch-all turns them into 500. The specification says a WebApplicationException whose response has no entity is passed to an applicable mapper, while one with an entity should be used directly, but implementations and versions differ, so a broad mapper can still swallow both cases. The fix is an ExceptionMapper<WebApplicationException> that returns e.getResponse(), optionally as a problem body, or a catch-all that checks for WebApplicationException first, plus tests that assert 404 for an unknown path.

Why this question is asked

This bug often appears right after someone adds a catch-all mapper to make sure no stack trace leaks. Suddenly typos in URLs return 500, monitoring fills with error alerts, and a deliberate 409 conflict reaches the client as a generic failure. Interviewers ask it to see whether we understand how the runtime treats its own HTTP exceptions and how mapper selection works. In this answer, we will recap the WebApplicationException family, reproduce both cases, read the specification's rule and see why the catch-all applies, fix it in two ways, adjust logging, and add regression tests.

1A Quick Recap of WebApplicationException

WebApplicationException is the JAX-RS exception that carries an HTTP response. We can throw it with a ready-made Response, as in the question, or use one of its subclasses for common statuses: NotFoundException for 404, NotAllowedException for 405, NotSupportedException for 415, NotAcceptableException for 406, BadRequestException for 400 and so on, all subclasses of ClientErrorException or ServerErrorException.

The runtime uses the same classes for its own decisions. When no resource matches the path, it throws a NotFoundException; when the path matches but the HTTP method does not, a NotAllowedException. So from the mapper's point of view, a 404 for a typo in the URL is just another exception passing through.

2Reproducing Both Cases

Here are the catch-all mapper and the resource from the question.

Java
@Provider
public class CatchAllMapper implements ExceptionMapper<Throwable> {
public Response toResponse(Throwable e) {
log.error("Unexpected", e);
return Response.serverError()
.entity(new Problem("about:blank", "Internal Server Error", 500, null, null)).build(); // always 500
}
}
@POST @Path("orders/{id}/cancel")
public void cancel(@PathParam("id") long id) {
if (alreadyShipped(id)) {
throw new WebApplicationException(Response.status(409).entity(body).build());
}
}
// POST /orders/7/cancel (shipped) -> expected 409, got 500 (on some runtimes and versions)
// GET /ordres/7 (typo) -> expected 404, got 500, and an ERROR log line

3Why the Catch-all Applies

Mapper selection uses class distance: the runtime picks the mapper whose generic type is the nearest superclass of the thrown exception. NotFoundException extends ClientErrorException, which extends WebApplicationException, which extends RuntimeException, Exception and finally Throwable. If the only mapper is for Throwable, it is the nearest one for everything, so every exception, including the runtime's own 404s, goes through it, and it returns 500.

For WebApplicationException, the specification adds a special rule. If the exception's response has no entity and a mapper applies, the runtime must use the mapper; otherwise it uses the exception's response directly. The runtime's NotFoundException for an unknown path has no entity, so by the rule our catch-all is used, and that explains the second case completely. Our 409 carries an entity, so by the rule it should go to the client untouched. But implementations have not always agreed on this rule across versions, and frameworks can wrap exceptions on the way, so with a Throwable mapper present the 409 can still be swallowed. Check your version; the safe design does not depend on that detail.

Step throughHow a WebApplicationException reaches the client
  1. Exception thrownBy our code or by the runtime
  2. Is it a WebApplicationException?
    YesCheck its responseNoUse the nearest-superclass mapper
  3. Response has an entity?
    YesSend the response as is (per spec)NoUse the nearest applicable mapper
  4. Throwable mapper is the nearestReturns 500 for 404, 405, 415

4 steps in order. Play them, or step through them one at a time.

4Fix 1: A Mapper for WebApplicationException

The cleanest fix is a dedicated mapper for WebApplicationException. Because it is closer in the class hierarchy than Throwable, it wins for every WebApplicationException and subclass, and the catch-all is left for truly unexpected errors.

Java
@Provider
public class WebAppExceptionMapper implements ExceptionMapper<WebApplicationException> {
@Override
public Response toResponse(WebApplicationException e) {
Response original = e.getResponse();
if (original.hasEntity()) return original; // our 409 with its body
Response.StatusType s = original.getStatusInfo();
Problem body = new Problem("about:blank", s.getReasonPhrase(), s.getStatusCode(), null, null);
return Response.fromResponse(original) // keeps headers such as Allow
.type("application/problem+json")
.entity(body)
.build();
}
}
// POST /orders/7/cancel (shipped) -> 409 with the original body
// GET /ordres/7 -> 404 {"title":"Not Found","status":404,...}
// DELETE /orders (GET only) -> 405 with Allow: GET, problem body

Notice Response.fromResponse. A 405 from the runtime carries an Allow header listing the permitted methods, and building a brand new response would drop it. Copying the original keeps such headers while we add the problem body, so every error now has the same format.

5Fix 2: Check First in the Catch-all

If we prefer a single mapper, the catch-all can test for WebApplicationException before anything else and return its response, as in the code below. It works, but the dedicated mapper is clearer, because each mapper then has one job.

Java
public Response toResponse(Throwable e) {
if (e instanceof WebApplicationException w) return w.getResponse(); // 404, 405, 409 pass through
String id = correlationId();
log.error("Unexpected error, correlationId={}", id, e);
return Response.serverError().type("application/problem+json").entity(Problem.internal(id)).build();
}

Either way, the Throwable mapper keeps its real purpose: unexpected failures get one ERROR log line with a correlation id and a generic 500 without internals.

6Logging and Regression Tests

Expected client errors are not server errors, so the WebApplicationException mapper logs 4xx responses at debug or info level, if at all, and only 5xx at warn or error. Otherwise scanners hitting random URLs fill the error logs and hide real problems, and alerts on error rate become noise.

Then we add tests that would have caught this: a request to an unknown path expects 404, a wrong method expects 405 with an Allow header, an unsupported Content-Type expects 415, and the cancel endpoint for a shipped order expects 409 with its body. These are cheap to run with the runtime's in-memory test support or REST Assured against a started application, and they protect the mapping behaviour across runtime upgrades.

7Follow-up questions

Why not just remove the catch-all mapper?

Then unexpected exceptions get the runtime's default handling, which may be an HTML error page, a stack trace in development mode or a body in a different format. A catch-all is good practice; it only has to leave WebApplicationException alone.

Does the order of registration decide which mapper wins?

No. Selection is by the exception's class hierarchy, nearest superclass first, not by registration order. Order or priority only matters if two mappers are registered for exactly the same exception type, which should be avoided.

How would you return the 409 with a problem body instead of a custom one?

Throw a domain exception such as OrderAlreadyShippedException and give it its own mapper that returns 409 with a problem body and a stable error type. That keeps HTTP details out of the resource and makes the error format consistent.

8Conclusion

In this answer, we saw that an ExceptionMapper<Throwable> is the nearest mapper for every WebApplicationException, including the runtime's own 404, 405 and 415 exceptions, so it turns them into 500. The specification passes entity-less WebApplicationExceptions to mappers and uses responses with entities directly, but behaviour has varied, so we do not rely on it. A dedicated ExceptionMapper<WebApplicationException> that returns or enriches e.getResponse(), quieter logging for 4xx, and tests for unknown paths and deliberate conflicts fix the problem and keep it fixed.

What to say in the interviewAbout 100 seconds aloud

Open with

The cause is the catch-all mapper. Mappers are chosen by the nearest superclass of the thrown exception, and Throwable is a superclass of everything, including WebApplicationException and its subclasses.

Then, if they want more

The runtime itself throws those for its own decisions: NotFoundException when no path matches, NotAllowedException for a wrong method, NotSupportedException for a wrong media type. So with only a Throwable mapper, every one of them goes through it and becomes a 500, and gets logged as an error.

The specification has a special rule for WebApplicationException: if its response has no entity and a mapper applies, the mapper is used; if it has an entity, the response should be used directly. That explains the unknown-path case exactly, because the runtime's 404 has no entity.

Our 409 has an entity, so it should pass through, but implementations and versions have behaved differently, so I would not rely on it. The fix is to add an ExceptionMapper for WebApplicationException, which is nearer than Throwable and therefore wins.

It returns e.getResponse() when it has an entity, and otherwise uses Response.fromResponse to keep headers like Allow and adds a problem details body. Alternatively the catch-all can check instanceof WebApplicationException first. The Throwable mapper stays for genuinely unexpected errors with one error log and a correlation id, while 4xx responses are logged quietly.

And I would add tests: unknown path expects 404, wrong method expects 405, and the conflict expects 409 with its body.

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 "A resource throws new...": https://scrivio-interview-library.netlify.app/java/jax-rs/f72806a739/