Error Handling Strategy
Error Response Structure
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Request validation failed",
"details": [
{
"field": "email",
"code": "INVALID_FORMAT",
"message": "Must be a valid email address",
"rejectedValue": "not-an-email"
}
],
"timestamp": "2025-01-15T10:30:00Z",
"traceId": "abc-123-def",
"documentation": "https://api.example.com/docs/errors#VALIDATION_ERROR"
}
}
Error Categories
| Category | Status | Example |
|---|---|---|
| Client errors | 4xx | Invalid input, unauthorized |
| Server errors | 500 | Unexpected failures |
| Business errors | 422 | Rule violations |
| Transient errors | 503 | Temporary unavailability |
Global Exception Handler (Spring)
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ErrorResponse> handleNotFound(
ResourceNotFoundException ex) {
return ResponseEntity.status(404).body(
ErrorResponse.builder()
.code("RESOURCE_NOT_FOUND")
.message(ex.getMessage())
.timestamp(Instant.now())
.build()
);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ErrorResponse> handleValidation(
MethodArgumentNotValidException ex) {
List<FieldError> errors = ex.getBindingResult()
.getFieldErrors().stream()
.map(e -> new FieldError(e.getField(), e.getDefaultMessage()))
.collect(Collectors.toList());
return ResponseEntity.status(422).body(
ErrorResponse.builder()
.code("VALIDATION_ERROR")
.message("Validation failed")
.details(errors)
.build()
);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleGeneral(Exception ex) {
log.error("Unexpected error", ex);
return ResponseEntity.status(500).body(
ErrorResponse.builder()
.code("INTERNAL_ERROR")
.message("An unexpected error occurred")
.traceId(MDC.get("traceId"))
.build()
);
}
}
API Best Practices
Design Principles
- Use nouns, not verbs
- Plural resource names
- Consistent naming conventions
- Proper HTTP status codes
Versioning
- URI versioning (/v1/resource)
- Header versioning
- Deprecation policy
Documentation
- OpenAPI/Swagger specs
- Request/Response examples
- Error code documentation
- Rate limit documentation
Key Points
- Understanding API Error 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 API Error Handling in a backend system. Consider scalability, error handling, and production readiness.
Solution
// API Error Handling implementation
// Key aspects: validation, error handling, logging, testing
public class APIErrorHandling {
// Production-ready implementation
}Identify and handle edge cases for API Error 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 API Error 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 should you NEVER include in error responses to clients?
2. What is the purpose of a global exception handler?
3. What is the primary purpose of API Error Handling?
4. What is a common mistake when implementing API Error Handling?
Flashcards
Question
What should error responses include?
Click to reveal answer
Answer
Code, message, details, timestamp, traceId (no stack traces)
Question
Spring global exception handler annotation?
Click to reveal answer
Answer
@RestControllerAdvice + @ExceptionHandler
Question
What is API Error Handling?
Click to reveal answer
Answer
API Error Handling is a key concept in backend development.
Question
When to use API Error Handling?
Click to reveal answer
Answer
Use API Error Handling when building production systems that require reliability, scalability, and maintainability.
Question
API Error 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.Always return consistent error response format
- 2.Never expose internal details (stack traces, SQL queries)
- 3.Use global exception handler for centralized error handling
- 4.Include traceId for debugging, documentation URL for help
Interview Tips
- •Design error responses
- •Know Spring exception handling patterns
Cheat Sheet
Error Handling
- Response: { code, message, details, timestamp, traceId }
- Never expose: Stack traces, SQL queries, internal details
- Spring: @RestControllerAdvice + @ExceptionHandler
- Categories: 4xx=client, 5xx=server, 422=business, 503=transient