Your routes send errors as JSON. But when a path has no route at all, like /contact, none of your code runs: Spring throws a NoResourceFoundException and answers by itself, with its own 404 page. A browser can show it, but a program that expects JSON can't read it.
Spring lets you replace that page with an exception handler: a method marked @ExceptionHandler with the exception it handles, inside a class marked @RestControllerAdvice. When Spring hits that exception, it calls the method with the exception it caught and sends what the method returns. Here is a handler for another exception (not part of this lesson):
@RestControllerAdvice
class CrashHandler {
@ExceptionHandler(IllegalStateException.class)
Object crashed(IllegalStateException error) {
return ResponseEntity.status(500).body(Map.of("error", "Something went wrong"));
}
}
A handler only runs for the exception it names. A route that returns its own 404, like getProduct, keeps its own message. GET /products/abc still gets Spring's 400 page: the route matches, but abc can't become an int. And a 405 still gets Spring's page too. The requests and answers your code must give, in this order:
GET /contact → 404 {"error": "Not found"}
GET /products/abc → 400 (Spring's own page, as before)
POST /orders {"product_id": 1, "quantity": 2} → 404 {"error": "Not found"}
GET /products/9 → 404 {"error": "Product not found"}
DELETE /products → 405 (Spring's own page, as before)
GET /about → 200 {"name": "Corner Shop", "currency": "USD"}
Your task: below ShopController, add a @RestControllerAdvice class NotFoundHandler with a method notFound(NoResourceFoundException error), marked @ExceptionHandler(NoResourceFoundException.class), that answers {"error": "Not found"} with status 404 through your errorResponse helper.
Assignment
Follow the Coding Tutorial to add an exception handler that answers unknown paths in JSON.
Hint
The imports are already at the top. errorResponse is static and lives in ShopController, so from NotFoundHandler you call it with the class name in front: ShopController.errorResponse(...).
Free plan: 30 tutor messages. PRO is unlimited.
