Sobes.tech
Junior — Middle

What tools do you use for exception handling in Spring MVC controllers?

sobes.tech AI

Answer from AI

In Spring MVC, exception handling in controllers is usually managed using:

  • The @ExceptionHandler annotation within a controller for handling specific exceptions.
  • A class annotated with @ControllerAdvice for global exception handling across all controllers.

Example of using @ExceptionHandler:

@Controller
public class MyController {

    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<String> handleNotFound(ResourceNotFoundException ex) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
    }

    // controller methods
}

Example of global handling with @ControllerAdvice:

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleAllExceptions(Exception ex) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("An error occurred: " + ex.getMessage());
    }
}