Junior — Middle
What methods in Spring can be used to handle exceptional situations?
sobes.tech AI
Answer from AI
In Spring, there are several approaches to handle exceptional situations:
- @ExceptionHandler — an annotation that allows you to define a method in a controller or in a class annotated with @ControllerAdvice, which will handle specific types of exceptions.
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<String> handleNotFound(ResourceNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
}
}
-
@ControllerAdvice — a class that centrally handles exceptions for all controllers.
-
ResponseStatusException — throwing an exception with a specific HTTP status.
-
HandlerExceptionResolver — an interface for lower-level exception handling.
-
Using filters and interceptors to catch exceptions at the HTTP request level.
Most often, it is sufficient to use @ExceptionHandler together with @ControllerAdvice for convenient and centralized error handling.