Sobes.tech
Junior — Middle

How to implement error handling in applications using Spring Web MVC?

sobes.tech AI

Answer from AI

In Spring Web MVC, error handling is implemented using annotations and special classes that allow centralized interception and processing of exceptions.

Main methods:

  1. @ExceptionHandler — an annotation for methods in a controller that handle specific exceptions.
@Controller
public class MyController {
    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<String> handleNotFound(ResourceNotFoundException ex) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
    }
}
  1. @ControllerAdvice — a class that globally handles exceptions for all controllers.
@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleAll(Exception ex) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Server error");
    }
}
  1. Using ResponseStatusException to throw exceptions with an HTTP status.

Thus, error handling becomes centralized and easier to maintain.

How to implement error handling in applications using… - sobes.tech