00:00

Spring Boot Exception Handling

Exception handling is an important part of any application to manage errors and provide meaningful responses to clients. Spring Boot provides several ways to handle exceptions globally or locally in your application.

1. Using @ExceptionHandler

The @ExceptionHandler annotation is used to handle exceptions in a specific controller.


@RestController
public class MyController {

    @GetMapping("/example")
    public String example() {
        if(true) {
            throw new RuntimeException("Something went wrong!");
        }
        return "Hello";
    }

    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<String> handleRuntimeException(RuntimeException ex) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ex.getMessage());
    }
}
    

2. Using @ControllerAdvice

@ControllerAdvice allows you to handle exceptions globally across all controllers.


@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<String> handleRuntimeException(RuntimeException ex) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Global Error: " + ex.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleException(Exception ex) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Global Exception: " + ex.getMessage());
    }
}
    

3. Using ResponseEntityExceptionHandler

You can extend ResponseEntityExceptionHandler to customize Spring Boot's default exception handling.


@ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {

    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(
            MethodArgumentNotValidException ex, 
            HttpHeaders headers, 
            HttpStatus status, 
            WebRequest request) {
        
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getFieldErrors().forEach(error -> {
            errors.put(error.getField(), error.getDefaultMessage());
        });
        return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
    }
}
    

4. Best Practices

  • Use @ControllerAdvice for global exception handling.
  • Create custom exception classes for better error identification.
  • Return meaningful HTTP status codes.
  • Log exceptions properly for debugging.
  • Provide user-friendly error messages instead of raw exception stack traces.

With these approaches, you can handle exceptions efficiently in Spring Boot applications.