Quick revision
The short answer
We add a method annotated @ExceptionHandler(OrderNotFoundException.class) to the controller and return either ResponseEntity.status(404).body(...) with our own record or a ProblemDetail with status 404, which Spring writes as JSON. A handler declared in a controller applies only to exceptions from that controller's methods, and when several handlers match, Spring picks the one whose exception type is the closest match.
What to remember
In this answer, we turned an OrderNotFoundException from a 500 into a proper 404. We wrote an @ExceptionHandler method in the controller, once with ResponseEntity.status(404).body(...) and once returning a ProblemDetail, and saw the JSON each produces. A handler in a controller applies only to that controller, global handlers live in @RestControllerAdvice, and when several handlers match, Spring chooses the one with the closest exception type.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We add a method annotated @ExceptionHandler(OrderNotFoundException.class) to the controller and return either ResponseEntity.status(404).body(...) with our own record or a ProblemDetail with status 404, which Spring writes as JSON. A handler declared in a controller applies only to exceptions from that controller's methods, and when several handlers match, Spring picks the one whose exception type is the closest match.
Why this question is asked
Returning the right status for a missing resource is one of the first things we do in any REST API. If we do nothing, an OrderNotFoundException thrown from a service reaches the servlet container and the client sees a 500, which says the server is broken when really the client asked for an order that does not exist. Interviewers ask this as a warm-up coding question, and the follow-up details, where the handler applies and which handler wins, show whether we understand how Spring finds it. In this answer, we will reproduce the 500, write the handler in two styles, see what the client receives, and then look at scope and how Spring chooses between matching handlers.
1The Problem Without a Handler
Here is the controller and the exception. The service throws when the order does not exist.
Spring MVC does not know what OrderNotFoundException means, so nothing maps it to a status, and Spring Boot's error page reports a 500.
2Writing the Handler With ResponseEntity
An @ExceptionHandler method is an ordinary controller method that Spring calls when a listed exception escapes from a handler method. It can take the exception as a parameter, and it can return anything a normal controller method can return. Here we return a ResponseEntity, which lets us set the status and the body explicitly.
Notice that we used ex.getMessage() only because we wrote that message ourselves and it is safe to show. For exceptions from libraries we would never echo the message, since it can contain internal details.
3Writing the Handler With ProblemDetail
Since Spring Framework 6, we can return a ProblemDetail instead, the standard error shape from RFC 9457. Spring writes it as JSON with the media type application/problem+json and takes the HTTP status from the object, so no ResponseEntity is needed.
The custom property orderId appears at the top level of the JSON, next to the standard fields. If a team has a company error format, ProblemDetail is usually its base, so this style is the one we would choose for a new service.
4Where the Handler Applies
A handler declared inside a controller is local: it handles exceptions thrown by that controller's own request methods and by nothing else. If ProductController also lets an OrderNotFoundException escape, this handler does not see it. That is useful for an exception that only one controller can produce, or for a controller that needs a different response from the rest of the application.
For handlers that should apply everywhere, we move the method into a class annotated with @RestControllerAdvice. Spring checks the controller's own handlers first and the advice classes only if no local handler matched, so a local handler can override a global one for one controller.
5Which Handler Wins When Several Match
A handler can match the exception's own type or any of its superclasses. When a controller has several handlers that match, Spring does not take the first one in the file; it picks the one whose declared type is closest to the thrown type in the class hierarchy.
| Thrown exception | Matching handlers | Chosen |
|---|---|---|
OrderNotFoundException | OrderNotFoundException (0), RuntimeException (1) | handleNotFound |
IllegalStateException | RuntimeException (1) | handleAny |
| IOException (checked) | none in this controller | advice or /error |
Spring measures the distance with an internal comparator that counts the steps up the class hierarchy, and the smallest distance wins. Spring also looks at the exception's cause chain, so a handler for OrderNotFoundException still matches when that exception arrives wrapped inside another one, although a match on the top-level exception is preferred. Check your version for the exact cause matching rules.
6Follow-up questions
What is the difference between this and @ResponseStatus on the exception class?
@ResponseStatus(HttpStatus.NOT_FOUND) on the exception class is shorter and maps the exception to 404 everywhere, but we do not control the body; Spring calls response.sendError and Spring Boot's error page renders a default JSON. An @ExceptionHandler gives full control of the body and can be local to one controller, so it is the better choice when the response format matters.
Can one handler cover several exception types?
Yes. We list them, for example @ExceptionHandler({OrderNotFoundException.class, CustomerNotFoundException.class}), and declare the parameter as a common supertype such as NotFoundException or RuntimeException. Often a better design is a common base class like NotFoundException, so one handler covers every new subclass automatically.
Should the service throw OrderNotFoundException or return Optional?
Both are fine. Repositories commonly return Optional, and the service or controller decides that absence is an error, for example orders.findById(id).orElseThrow(() -> new OrderNotFoundException(id)). The exception then carries the id, and the handler turns it into a 404 in one place.
7Conclusion
In this answer, we turned an OrderNotFoundException from a 500 into a proper 404. We wrote an @ExceptionHandler method in the controller, once with ResponseEntity.status(404).body(...) and once returning a ProblemDetail, and saw the JSON each produces. A handler in a controller applies only to that controller, global handlers live in @RestControllerAdvice, and when several handlers match, Spring chooses the one with the closest exception type.
Open with
I'd add a method in the controller annotated with @ExceptionHandler and the class OrderNotFoundException, taking the exception as a parameter. It can return a ResponseEntity, so ResponseEntity.status of NOT_FOUND with a small record body holding a code, the message and the order id.
Then, if they want more
Or, the way I'd do it in a new service, it returns a ProblemDetail created with forStatusAndDetail of NOT_FOUND and the message, with a title and an orderId property. Spring takes the status from the ProblemDetail and writes it as application/problem+json, with the custom property at the top level.
Without the handler, Spring doesn't know the exception, so the client would get a 500. Two things about matching. A handler declared inside a controller only applies to exceptions from that controller's methods. If I want it for every controller, I move it to a @RestControllerAdvice, and local handlers are checked first, so they can override the global ones.
And when several handlers match, say one for RuntimeException and one for OrderNotFoundException, Spring doesn't take the first declared; it picks the closest type in the exception hierarchy, so the specific handler wins. I'd only echo the message because I wrote it myself.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Spring Framework 6
- 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
- Spring Framework reference, Spring Web MVC
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 @ExceptionHandler that maps OrderNotFoundException to 404 with a JSON body...": https://scrivio-interview-library.netlify.app/spring-boot/error-handling/c865caf80b/