Careeroza
Why Centralized Error Handling
The Problem
Without a plan, every controller method has its own try/catch and its own error JSON. One endpoint returns {"error": "..."}, another {"message": "..."}, and an unexpected exception returns a 500 with a stack-trace-like body. Frontend and mobile developers hate this.
The Spring way: throw meaningful exceptions from the service layer, and handle them in one place.
ProductService.getById(42)
throws ProductNotFoundException("Product 42 not found")
|
v
DispatcherServlet catches it
|
v
@RestControllerAdvice -> @ExceptionHandler(ProductNotFoundException.class)
|
v
404 application/problem+json {"title":"Product not found","status":404,...}Spring Boot Default Errors
| Situation | Default status |
|---|---|
| Your code throws any uncaught exception | 500 Internal Server Error |
| Bad JSON / type mismatch / missing required param | 400 Bad Request |
@Valid fails | 400 Bad Request |
| No mapping for the URL | 404 Not Found |
| Wrong HTTP method | 405 Method Not Allowed |
| Wrong Content-Type | 415 Unsupported Media Type |
Tip: Set spring.mvc.problemdetails.enabled=true to make Spring's own errors (405, 415, validation...) use the standard ProblemDetail format too.