The simplest way to map a domain exception to an HTTP code, with no handler class at all.
@ResponseStatus(HttpStatus.NOT_FOUND)
class OrderNotFound extends RuntimeException {
OrderNotFound(Long id) { super("No order " + id); }
}
// or without an annotation:
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "No order 42");
HTTP/1.1 404 Not Found
{"status":404,"error":"Not Found","message":"No order 42"}
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-08-11