WayrApp Backend & Ecosystem Documentation - v1.0.0
    Preparing search index...

    Function errorHandler

    • Global Error Handler Middleware for WayrApp Backend API

      A comprehensive Express error handling middleware that provides centralized error processing for the entire WayrApp language learning platform backend. This middleware serves as the final error processing layer in the Express middleware stack, catching and standardizing all errors that occur during request processing across all API endpoints.

      The error handler intelligently processes different types of errors including custom AppErrors, Zod validation errors, Prisma database errors, and generic JavaScript errors. It transforms these various error types into a consistent API response format that clients can reliably parse and handle. The middleware also provides comprehensive error logging with request context for debugging and monitoring purposes.

      This middleware is essential for the application's distributed architecture evolution, as it ensures consistent error handling across all nodes and services. It's configured in the main Express application (src/app.ts) as the final middleware in the stack, ensuring all unhandled errors are properly caught and formatted before being sent to clients.

      The error handler supports the application's security posture by sanitizing error messages in production environments and providing detailed error information only when appropriate. It integrates with the application's logging system to provide comprehensive error tracking and monitoring capabilities.

      Error Type Handling:

      • AppError: Returns custom status code and error code with original message
      • ZodError: Returns 400 BAD_REQUEST with detailed validation error information
      • PrismaClientKnownRequestError: Maps specific Prisma error codes to appropriate HTTP statuses
        • P2002: Unique constraint violation → 409 CONFLICT
        • P2025: Record not found → 404 NOT_FOUND
        • Others: Generic database error → 400 BAD_REQUEST
      • PrismaClientValidationError: Returns 400 BAD_REQUEST for invalid data
      • Generic Error: Returns 500 INTERNAL_SERVER_ERROR with sanitized message

      Logging Features:

      • Logs all errors with full stack traces
      • Includes request context (URL, method, IP, user agent)
      • Provides structured logging for monitoring and debugging
      • Maintains error correlation for distributed tracing

      Security Considerations:

      • Sanitizes error messages to prevent information leakage
      • Provides consistent error format regardless of error source
      • Logs sensitive information server-side while sending safe messages to clients

      Parameters

      • error: Error

        The error object to be processed and formatted

      • req: Request

        Express request object containing request context

      • res: Response

        Express response object for sending the error response

      • _next: NextFunction

        Express next function (unused in error handlers)

      Returns void

      Sends JSON error response to client and terminates request

      // Primary usage in main Express application (src/app.ts)
      import { errorHandler } from '@/shared/middleware';

      const app = express();

      // ... other middleware and routes

      // Error handler must be the last middleware
      app.use(errorHandler);
      // The middleware automatically handles different error types:
      //
      // AppError -> Returns structured error with custom status and code
      // ZodError -> Returns 400 with validation details
      // Prisma errors -> Returns appropriate status based on error type
      // Generic errors -> Returns 500 with sanitized message
      // Error response format sent to clients:
      // {
      // "error": {
      // "code": "VALIDATION_ERROR",
      // "message": "Email is required",
      // "details": { "field": "email", "message": "Required" },
      // "timestamp": "2024-01-20T10:30:00.000Z",
      // "path": "/api/v1/auth/register"
      // }
      // }
      // Zod validation error response:
      // {
      // "error": {
      // "code": "VALIDATION_ERROR",
      // "message": "Validation failed",
      // "details": [
      // { "field": "email", "message": "Invalid email", "code": "invalid_string" },
      // { "field": "password", "message": "String must contain at least 8 character(s)", "code": "too_small" }
      // ],
      // "timestamp": "2024-01-20T10:30:00.000Z",
      // "path": "/api/v1/auth/register"
      // }
      // }
      // Prisma unique constraint error response:
      // {
      // "error": {
      // "code": "CONFLICT",
      // "message": "Unique constraint violation",
      // "details": { "field": ["email"] },
      // "timestamp": "2024-01-20T10:30:00.000Z",
      // "path": "/api/v1/users"
      // }
      // }

      @function errorHandler