Exception Handling
A Java error should become a clear HTTP response
A service can report an error with an exception: for example, the requested resource may not exist. If nothing is configured, the internal exception and the external HTTP contract become too tightly coupled. Spring MVC lets you describe separately how a particular error should look to the client.
@RestControllerAdvice
class ApiExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
ResponseEntity<ApiError> handle(UserNotFoundException ex) {
return ResponseEntity.status(404)
.body(new ApiError(ex.getMessage()));
}
}
@ExceptionHandler connects an exception type to a handling method.
@RestControllerAdvice lets you move such methods out of individual controllers
and apply them to the web layer centrally.
Why a centralized handler is useful
Without a shared layer, every controller starts repeating the same try/catch blocks
and formatting errors in its own way. Advice makes it possible to keep one error format and consistent rules
for mapping common exceptions to HTTP statuses.
Do not send internal exception details to the client unless necessary.
Stack traces, SQL text, and service messages are useful in logs, but an external API should usually return
a stable and safe error structure.
Check yourself
Exercise review
The mentor knows the solution and will help you reach it independently
Sign in to use the Mentor
The Mentor uses the current exercise and your conversation history.
Sign in
Review the key nuances and the answer after making your own attempt.
Sign in to view the solution
The solution and explanation are available after signing in.
Sign in