All files / src/middleware error-handler.ts

0% Statements 0/42
0% Branches 0/19
0% Functions 0/4
0% Lines 0/39

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172                                                                                                                                                                                                                                                                                                                                                       
import { Request, Response, NextFunction } from 'express';
import { AppError, ErrorCode } from '../types/errors';
import { Logger } from '../utils/logger';
 
export const errorHandler = (
  error: Error | AppError,
  req: Request,
  res: Response,
  next: NextFunction
): void => {
  const requestId = req.headers['x-request-id'] as string || 'unknown';
 
  // If it's already an AppError, use it directly
  if (error instanceof AppError) {
    Logger.error('Application error occurred', {
      requestId,
      error: {
        code: error.code,
        message: error.message,
        statusCode: error.statusCode,
        details: error.details,
        stack: error.stack
      },
      request: {
        method: req.method,
        url: req.url,
        userAgent: req.get('User-Agent'),
        ip: req.ip
      }
    });
 
    res.status(error.statusCode).json(error.toJSON());
    return;
  }
 
  // Handle known error types
  if (error.name === 'ValidationError') {
    const appError = new AppError(
      ErrorCode.VALIDATION_ERROR,
      'Erreur de validation',
      400,
      true,
      undefined,
      requestId
    );
 
    Logger.error('Validation error', {
      requestId,
      originalError: error.message,
      stack: error.stack
    });
 
    res.status(400).json(appError.toJSON());
    return;
  }
 
  if (error.name === 'UnauthorizedError') {
    const appError = new AppError(
      ErrorCode.UNAUTHORIZED,
      'Non autorisé',
      401,
      true,
      undefined,
      requestId
    );
 
    Logger.error('Unauthorized access attempt', {
      requestId,
      error: error.message,
      request: {
        method: req.method,
        url: req.url,
        ip: req.ip
      }
    });
 
    res.status(401).json(appError.toJSON());
    return;
  }
 
  // Handle JSON parsing errors (body-parser SyntaxError)
  if (
    error.name === 'SyntaxError' ||
    (typeof (error as any)?.type === 'string' && (error as any).type === 'entity.parse.failed')
  ) {
    const appError = new AppError(
      ErrorCode.VALIDATION_ERROR,
      'JSON invalide',
      400,
      true,
      undefined,
      requestId
    );
 
    Logger.error('JSON parse error', {
      requestId,
      originalError: (error as any)?.message,
      stack: (error as any)?.stack
    });
 
    res.status(400).json(appError.toJSON());
    return;
  }
 
  // Handle database errors
  if (error.message?.includes('database') || error.message?.includes('connection')) {
    const appError = new AppError(
      ErrorCode.DATABASE_ERROR,
      'Erreur de base de données',
      500,
      true,
      undefined,
      requestId
    );
 
    Logger.error('Database error', {
      requestId,
      error: error.message,
      stack: error.stack
    });
 
    res.status(500).json(appError.toJSON());
    return;
  }
 
  // Generic server error
  const appError = new AppError(
    ErrorCode.INTERNAL_SERVER_ERROR,
    'Erreur interne du serveur',
    500,
    false, // Non-operational error
    undefined,
    requestId
  );
 
  Logger.error('Unhandled error', {
    requestId,
    error: {
      name: error.name,
      message: error.message,
      stack: error.stack
    },
    request: {
      method: req.method,
      url: req.url,
      body: req.body,
      userAgent: req.get('User-Agent'),
      ip: req.ip
    }
  });
 
  res.status(500).json(appError.toJSON());
};
 
// Middleware to catch async errors
export const asyncHandler = (fn: Function) => {
  return (req: Request, res: Response, next: NextFunction) => {
    Promise.resolve(fn(req, res, next)).catch(next);
  };
};
 
// Request ID middleware
export const requestIdMiddleware = (req: Request, res: Response, next: NextFunction) => {
  const requestId = req.headers['x-request-id'] as string ||
    `req_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
 
  req.headers['x-request-id'] = requestId;
  res.setHeader('X-Request-ID', requestId);
 
  next();
};