Sobes.tech
Junior — Middle

What approaches to exception handling in Spring Framework are you familiar with?

sobes.tech AI

Answer from AI

In Spring Framework, I am familiar with several approaches to exception handling:

  • Using the @ExceptionHandler annotation in controllers to handle specific exceptions and return custom responses.

  • Global exception handling with a class annotated with @ControllerAdvice, where application errors can be centrally processed.

  • Overriding methods in ResponseEntityExceptionHandler to handle standard Spring MVC exceptions.

Example of a global handler:

@ControllerAdvice
public class GlobalExceptionHandler {

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

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleGeneral(Exception ex) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Internal server error");
    }
}

This approach allows centralized error management and improves API response quality.