Sobes.tech
Junior — Middle

How is exception handling implemented in controllers annotated with @Controller?

sobes.tech AI

Answer from AI

In Spring MVC controllers annotated with @Controller, exception handling can be performed in several ways:

  • @ExceptionHandler — a method within the controller or a separate class annotated with @ControllerAdvice, which intercepts exceptions of a specific type and returns a response.

  • @ControllerAdvice — a global exception handler for all controllers, allowing centralized error processing.

  • ResponseStatusException — throwing an exception with the @ResponseStatus annotation for automatic HTTP status setting.

Example of using @ExceptionHandler inside a controller:

@Controller
public class MyController {

    @GetMapping("/example")
    public String example() {
        if (true) {
            throw new IllegalArgumentException("Parameter error");
        }
        return "view";
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<String> handleIllegalArgument(IllegalArgumentException ex) {
        return ResponseEntity.badRequest().body(ex.getMessage());
    }
}

Thus, when an IllegalArgumentException occurs, the handleIllegalArgument method will return a response with a 400 status code and an error message.

How is exception handling implemented in controllers… - sobes.tech