Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 36 Β· REST Endpoints

Exception Mappers and Error Responses

Turn exceptions into clean HTTP error responses in Quarkus with @ServerExceptionMapper, WebApplicationException, ExceptionMapper and a consistent JSON problem format.

Things go wrong: a book is missing, a value is invalid, a downstream service is down. A good API answers with the right status code and a predictable body, never with a stack trace. In Quarkus REST you map exceptions to responses in one place, so endpoint code stays focused on the happy path.

The Quarkus code here is read-only. The runnable stand-ins model how Quarkus chooses a mapper and what a well-formed error body looks like.

Throwing the right exception

Jakarta REST ships with WebApplicationException and subclasses such as NotFoundException, BadRequestException, NotAuthorizedException, ForbiddenException and ClientErrorException. Throwing one produces that status:

Java
@GET
@Path("/{id}")
public BookDto one(@RestPath long id) {
    return repository.findByIdOptional(id)
            .map(BookDto::from)
            .orElseThrow(() -> new NotFoundException("No book with id " + id));
}

Uncaught exceptions of any other type become 500 Internal Server Error. Quarkus logs the stack trace on the server and hides details from the client, which is the right default.

Mapping your own exceptions

Define domain exceptions that say what went wrong in business terms:

Java
public class BookNotFound extends RuntimeException {
    public final long id;
    public BookNotFound(long id) {
        super("No book with id " + id);
        this.id = id;
    }
}

public class IsbnAlreadyUsed extends RuntimeException {
    public IsbnAlreadyUsed(String isbn) {
        super("ISBN already in the catalogue: " + isbn);
    }
}

Then map them to responses with @ServerExceptionMapper, a Quarkus REST annotation placed on a method in any class (a resource or a separate bean):

Java
import org.jboss.resteasy.reactive.server.ServerExceptionMapper;
import org.jboss.resteasy.reactive.RestResponse;

public class ErrorMappers {

    public record ApiError(String code, String message) {}

    @ServerExceptionMapper
    public RestResponse<ApiError> notFound(BookNotFound e) {
        return RestResponse.status(404, new ApiError("book_not_found", e.getMessage()));
    }

    @ServerExceptionMapper
    public RestResponse<ApiError> conflict(IsbnAlreadyUsed e) {
        return RestResponse.status(409, new ApiError("isbn_conflict", e.getMessage()));
    }
}

The exception type is the method parameter, so no extra registration is needed. If a mapper is declared inside a resource class it applies only to that class. In a separate bean class it applies to the whole application. A mapper method may also take ContainerRequestContext or UriInfo parameters when it needs request details, and it can return Uni<RestResponse<T>> for asynchronous work.

The standard way

Jakarta REST's own interface works too and is useful when you share code with non-Quarkus projects:

Java
import jakarta.ws.rs.ext.ExceptionMapper;
import jakarta.ws.rs.ext.Provider;

@Provider
public class IsbnMapper implements ExceptionMapper<IsbnAlreadyUsed> {
    @Override
    public Response toResponse(IsbnAlreadyUsed e) {
        return Response.status(409).entity(new ErrorMappers.ApiError("isbn_conflict", e.getMessage())).build();
    }
}

Which mapper wins?

If several mappers could handle an exception, the closest in the class hierarchy wins: a mapper for BookNotFound beats one for RuntimeException, which beats one for Throwable. The stand-in below walks up the superclass chain exactly like that.

Java Stand-in: the closest exception type wins

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

BookNotFound uses its own mapper (404). IsbnAlreadyUsed has none, so the parent AppException mapper answers (400). An unrelated exception reaches the default (500).

A consistent error format

Clients love a single, predictable error shape. A popular standard is RFC 9457 Problem Details (media type application/problem+json) with the members type, title, status, detail and instance. You can adopt it yourself, or add the community quarkus-resteasy-problem style extension later. The key idea is that every error, including validation errors, has the same fields.

For Bean Validation failures from the previous lesson, map ConstraintViolationException so each violation lists a field and message:

Java
@ServerExceptionMapper
public RestResponse<Map<String, Object>> invalid(ConstraintViolationException e) {
    var violations = e.getConstraintViolations().stream()
            .map(v -> Map.of("field", lastSegment(v.getPropertyPath().toString()),
                             "message", v.getMessage()))
            .toList();
    return RestResponse.status(400, Map.of("title", "Validation failed", "violations", violations));
}
Java Stand-in: building a problem-details body

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

One place for errors

Throw Business code throws a domain exception.
Map A mapper picks status and body.
Respond The client gets a stable error shape.

Endpoints stay free of try and catch.

1 / 2

Practical rules

  • Use 4xx for caller mistakes and 5xx for your mistakes. A missing book is 404; a database outage is 503 or 500.
  • Do not catch exceptions just to rethrow them as 500. Let the mapper decide.
  • Log once. Log unexpected exceptions in a catch-all mapper, not at every layer.
  • Do not leak secrets. Messages from exceptions may contain SQL or file paths. Map them to safe text.
  • Test errors. Each mapper deserves a test that checks status and body, as shown in Testing with @QuarkusTest.

Check your understanding

Quick check Β· 4 questions

of 4 answered You scored / 4 Β· perfect!

  1. 1. What does an uncaught, unmapped RuntimeException produce in a Quarkus REST endpoint?

    Unmapped exceptions become 500. The stack trace goes to the server log, not to the client.
  2. 2. How do you declare a Quarkus mapper for your BookNotFound exception?

    @ServerExceptionMapper methods are matched by their exception parameter type.
  3. 3. Two mappers exist, one for RuntimeException and one for BookNotFound (a subclass). Which handles a BookNotFound?

    The most specific mapper in the class hierarchy is chosen.
  4. 4. Why return the same JSON error shape everywhere?

    A stable error contract makes client code simple and reliable.

Summary

  • Throw WebApplicationException subclasses for quick cases and domain exceptions for business rules.
  • @ServerExceptionMapper (or ExceptionMapper) converts an exception into a RestResponse; the closest type wins.
  • Map validation errors and use one consistent body shape, ideally RFC 9457 Problem Details.
  • Hide internals from clients and log the details on the server.

Next: REST Client and Filters