Junior — Middle
How to implement exception and error handling in applications based on Spring Framework?
sobes.tech AI
Answer from AI
In Spring Framework, exception handling is implemented using several approaches:
- @ExceptionHandler — an annotation for methods in controllers that handle specific exceptions.
@Controller
public class MyController {
@ExceptionHandler(MyException.class)
public ResponseEntity<String> handleMyException(MyException ex) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ex.getMessage());
}
}
- @ControllerAdvice — a class that globally handles exceptions for all controllers.
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleAllExceptions(Exception ex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Server error");
}
}
- ResponseStatusException — allows throwing exceptions with a specific HTTP status.
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Resource not found");
- Using filters and interceptors for intercepting and handling exceptions at the HTTP request level.
Thus, Spring provides flexible mechanisms for centralized and local error handling, allowing to return understandable and correct responses to the client when exceptions occur.