Junior — Middle
How is exception handling implemented in applications using the Spring Framework?
sobes.tech AI
Answer from AI
In Spring Framework, exception handling is usually implemented using the @ExceptionHandler annotation in controllers or globally through @ControllerAdvice.
Example of local handling in a controller:
@RestController
public class MyController {
@GetMapping("/example")
public String example() {
if (true) {
throw new IllegalArgumentException("Parameter error");
}
return "OK";
}
@ExceptionHandler(IllegalArgumentException.class)
public ResponseEntity<String> handleIllegalArgument(IllegalArgumentException ex) {
return ResponseEntity.badRequest().body(ex.getMessage());
}
}
For global handling, create a class with @ControllerAdvice:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleAllExceptions(Exception ex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("Internal server error: " + ex.getMessage());
}
}
This approach allows centralized error handling, returning understandable responses to clients, and maintaining controller cleanliness.