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
- Validation: Always validate input at the boundary
- Error Handling: Use structured error responses
- Logging: Log key events for debugging
- Testing: Unit, integration, and load tests
- Documentation: Keep docs updated with code changes
Practice Problems
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
}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, idempotencyWrite 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 injectionQuiz
1. What annotation handles specific exceptions in a controller?
2. What HTTP status for ResourceNotFoundException?
3. What is the primary purpose of Exception Handling?
4. What is a common mistake when implementing Exception Handling?
Flashcards
Question
@ExceptionHandler purpose?
Click to reveal answer
Answer
Handle specific exception types and return error responses
Question
ResourceNotFoundException HTTP status?
Click to reveal answer
Answer
404 Not Found
Question
What is Exception Handling?
Click to reveal answer
Answer
Exception Handling is a key concept in backend development.
Question
When to use Exception Handling?
Click to reveal answer
Answer
Use Exception Handling when building production systems that require reliability, scalability, and maintainability.
Question
Exception Handling best practices
Click to reveal answer
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