Junior — Middle
What is the best way to structure exception handling in a project containing multiple REST controllers, each of which provides CRUD operations for different entities?
sobes.tech AI
Answer from AI
The best way to structure exception handling in a project with multiple REST controllers is to use a centralized exception handler. In Spring Boot, for example, this is done using the @ControllerAdvice annotation, which allows creating a class that handles exceptions thrown from any controllers.
Advantages of this approach:
- A single place for error handling and forming responses to the client.
- Simplifies controller code — they do not need to handle exceptions locally.
- Easy to maintain and extend error handling.
Example:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(EntityNotFoundException.class)
public ResponseEntity<String> handleNotFound(EntityNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
}
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleGeneric(Exception ex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Internal server error");
}
}
Thus, all controllers can throw exceptions, and @ControllerAdvice will catch them and generate correct HTTP responses.