All files / backend/src/api/middleware error-handler.ts

14.28% Statements 1/7
0% Branches 0/4
33.33% Functions 1/3
14.28% Lines 1/7

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                                            8x                                                      
/**
 * Error Handler Middleware
 *
 * Centralized error handling for API requests.
 */
 
import type { Request, Response, NextFunction } from 'express';
 
/**
 * Error response format
 */
export interface ErrorResponse {
  error: string;
  stack?: string;
}
 
/**
 * Wrap an async handler to catch errors
 */
export function asyncHandler(
  fn: (req: Request, res: Response, next: NextFunction) => Promise<unknown>
) {
  return (req: Request, res: Response, next: NextFunction) => {
    Promise.resolve(fn(req, res, next)).catch(next);
  };
}
 
/**
 * Global error handler middleware
 */
export function errorHandler(
  error: Error,
  req: Request,
  res: Response,
  next: NextFunction
) {
  console.error('API Error:', error);
 
  const response: ErrorResponse = {
    error: error.message || 'Something went wrong.',
  };
 
  // Include stack trace in development
  if (process.env.NODE_ENV === 'development') {
    response.stack = error.stack;
  }
 
  res.status(500).json(response);
}