Skip to content
beginnerPhase ·

Error Handling

Design consistent error responses with error codes and messages.

40m
0 problems
Topic Progress0%

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

  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 API Error Handling

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
}
API Error Handling Edge Cases

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, idempotency
API Error Handling Testing Strategy

Write 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 injection

Quiz

1. What should you NEVER include in error responses to clients?

Question 1 options

2. What is the purpose of a global exception handler?

Question 2 options

3. What is the primary purpose of API Error Handling?

Question 3 options

4. What is a common mistake when implementing API Error Handling?

Question 4 options

Flashcards

Question

What should error responses include?

Answer

Code, message, details, timestamp, traceId (no stack traces)

Question

Spring global exception handler annotation?

Answer

@RestControllerAdvice + @ExceptionHandler

Question

What is API Error Handling?

Answer

API Error Handling is a key concept in backend development.

Question

When to use API Error Handling?

Answer

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

Question

API Error Handling best practices

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