Skip to content
intermediatePhase ·

Exception Handling in Spring

Handle exceptions using @ExceptionHandler.

35m
0 problems
Topic Progress0%

Exception Handling

@ExceptionHandler

@RestController
public class ProductController {

    @GetMapping("/{id}")
    public ResponseEntity<Product> getProduct(@PathVariable Long id) {
        Product product = productService.findById(id)
            .orElseThrow(() -> new ResourceNotFoundException(
                "Product not found with id: " + id));
        return ResponseEntity.ok(product);
    }

    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<ErrorResponse> handleNotFound(
            ResourceNotFoundException ex) {
        return ResponseEntity.status(404).body(
            new ErrorResponse("NOT_FOUND", ex.getMessage()));
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ErrorResponse> handleValidation(
            MethodArgumentNotValidException ex) {
        String message = ex.getBindingResult().getFieldErrors().stream()
            .map(e -> e.getField() + ": " + e.getDefaultMessage())
            .collect(Collectors.joining(", "));
        return ResponseEntity.status(422).body(
            new ErrorResponse("VALIDATION_ERROR", message));
    }
}

Exception Response Format

{
  "code": "RESOURCE_NOT_FOUND",
  "message": "Product not found with id: 123",
  "timestamp": "2025-01-15T10:30:00Z"
}

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 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 Exception Handling

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

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

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

Identify and handle edge cases for 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
Exception Handling Testing Strategy

Write a testing strategy for 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 annotation handles specific exceptions in a controller?

Question 1 options

2. What HTTP status for ResourceNotFoundException?

Question 2 options

3. What is the primary purpose of Exception Handling?

Question 3 options

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

Question 4 options

Flashcards

Question

@ExceptionHandler purpose?

Answer

Handle specific exception types and return error responses

Question

ResourceNotFoundException HTTP status?

Answer

404 Not Found

Question

What is Exception Handling?

Answer

Exception Handling is a key concept in backend development.

Question

When to use Exception Handling?

Answer

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

Question

Exception Handling best practices

Answer

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

Revision Notes

Key Takeaways

  • 1.@ExceptionHandler catches specific exceptions
  • 2.Return proper HTTP status codes for errors
  • 3.Create custom exception classes for business errors
  • 4.Always log exceptions for debugging

Interview Tips

  • Implement exception handling in controllers
  • Know exception-to-status-code mapping

Cheat Sheet

Exception Handling

  • @ExceptionHandler: Handle specific exceptions
  • @ControllerAdvice: Global exception handling
  • 404: ResourceNotFoundException
  • 422: ValidationException
  • 500: Unexpected exceptions
  • Always: Log exceptions, return structured errors