Skip to content
intermediatePhase ·

Global Exception Handling

Create centralized exception handlers for consistent error responses.

35m
0 problems
Topic Progress0%

Global Exception Handling

Global exception handling catches exceptions in one place and returns consistent error responses across your entire API.

@ControllerAdvice — The Global Handler

@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    // Handle custom application exceptions
    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<ErrorResponse> handleNotFound(ResourceNotFoundException ex) {
        log.warn("Resource not found: {}", ex.getMessage());
        return ResponseEntity.status(HttpStatus.NOT_FOUND)
            .body(new ErrorResponse(ex.getErrorCode(), ex.getMessage()));
    }

    @ExceptionHandler(DuplicateResourceException.class)
    public ResponseEntity<ErrorResponse> handleDuplicate(DuplicateResourceException ex) {
        log.warn("Duplicate resource: {}", ex.getMessage());
        return ResponseEntity.status(HttpStatus.CONFLICT)
            .body(new ErrorResponse(ex.getErrorCode(), ex.getMessage()));
    }

    @ExceptionHandler(InsufficientStockException.class)
    public ResponseEntity<ErrorResponse> handleInsufficientStock(InsufficientStockException ex) {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST)
            .body(new ErrorResponse(ex.getErrorCode(), ex.getMessage()));
    }

    // Handle validation errors
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ErrorResponse> handleValidation(MethodArgumentNotValidException ex) {
        List<String> errors = ex.getBindingResult().getFieldErrors().stream()
            .map(error -> error.getField() + ": " + error.getDefaultMessage())
            .toList();

        return ResponseEntity.badRequest()
            .body(new ErrorResponse("VALIDATION_FAILED", "Validation failed", errors));
    }

    // Handle generic exceptions (catch-all)
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ErrorResponse> handleGeneric(Exception ex) {
        log.error("Unexpected error: {}", ex.getMessage(), ex);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
            .body(new ErrorResponse("INTERNAL_ERROR", "An unexpected error occurred"));
    }
}

ErrorResponse DTO

public class ErrorResponse {
    private String errorCode;
    private String message;
    private List<String> details;
    private LocalDateTime timestamp;

    public ErrorResponse(String errorCode, String message) {
        this.errorCode = errorCode;
        this.message = message;
        this.details = new ArrayList<>();
        this.timestamp = LocalDateTime.now();
    }
}

Exception Patterns

Custom Exceptions

public class NotFoundException extends RuntimeException {
    public NotFoundException(String message) {
        super(message);
    }
}

Handling

  • Catch specific exceptions
  • Handle at appropriate layer
  • Log with context
  • Return meaningful errors

Best Practices

  • Use unchecked exceptions for bugs
  • Use checked exceptions for recoverable
  • Don't catch and ignore
  • Include correlation IDs

Key Points

  • Understanding Global Exception Handling is essential for production systems
  • Always consider scalability and maintainability
  • Test thoroughly before deploying to production
  • Monitor performance and set up alerting

Common Patterns

  1. Validation: Always validate input at the boundary
  2. Error Handling: Use structured error responses
  3. Logging: Log key events for debugging
  4. Testing: Unit, integration, and load tests
  5. Documentation: Keep docs updated with code changes

Practice Problems

0/3solved
Implement Global Exception Handling

Design and implement a solution for Global Exception Handling in a backend system. Consider scalability, error handling, and production readiness.

Solution
// Global Exception Handling implementation
// Key aspects: validation, error handling, logging, testing

public class GlobalExceptionHandling {
    // Production-ready implementation
}
Global Exception Handling Edge Cases

Identify and handle edge cases for Global Exception Handling. What happens under high load, with invalid input, or during failures?

Solution
// Edge case handling:
// 1. Null/empty input -> validation
// 2. High load -> rate limiting, queuing
// 3. Failures -> retries, circuit breaker
// 4. Concurrent access -> locks, idempotency
Global Exception Handling Testing Strategy

Write a testing strategy for Global Exception Handling. Include unit tests, integration tests, and performance tests.

Solution
// Test plan:
// - Unit: 80% coverage target
// - Integration: API contracts
// - Performance: latency, throughput
// - Chaos: failure injection

Quiz

1. What does @RestControllerAdvice do?

Question 1 options

2. Why should specific exception handlers be declared before generic ones?

Question 2 options

3. What is the primary purpose of Global Exception Handling?

Question 3 options

4. What is a common mistake when implementing Global Exception Handling?

Question 4 options

Flashcards

Question

What is @RestControllerAdvice?

Answer

Global exception handler that catches exceptions from all controllers

Question

What is a standard error response?

Answer

JSON with errorCode, message, details, and timestamp

Question

What is Global Exception Handling?

Answer

Global Exception Handling is a key concept in backend development.

Question

When to use Global Exception Handling?

Answer

Use Global Exception Handling when building production systems that require reliability, scalability, and maintainability.

Question

Global Exception Handling best practices

Answer

Follow SOLID principles, write clean code, test thoroughly, document decisions, and monitor in production.

Revision Notes

Key Takeaways

  • 1.@RestControllerAdvice creates a global exception handler for all controllers
  • 2.Return consistent error responses with errorCode, message, details, and timestamp
  • 3.Handle specific exceptions (ResourceNotFoundException, ValidationException) before generic ones
  • 4.Log exceptions at appropriate levels (WARN for expected, ERROR for unexpected)
  • 5.Use @ExceptionHandler to map specific exceptions to HTTP status codes

Interview Tips

  • Explain how @RestControllerAdvice differs from try-catch in each controller (centralized vs scattered)
  • Discuss designing consistent error response formats for API consumers
  • Know how to handle validation errors from @Valid and return meaningful error messages

Cheat Sheet

Global Exception Handling

  • @RestControllerAdvice: global handler for all controllers
  • @ExceptionHandler(ExceptionClass.class): map exception to response
  • Return ResponseEntity with appropriate HTTP status
  • Error response: {errorCode, message, details, timestamp}
  • Handle specific exceptions before generic ones
  • Log warnings for expected errors, errors for unexpected
  • Catch MethodArgumentNotValidException for @Valid errors