All files / src/common/filters http-exception.filter.ts

100% Statements 26/26
100% Branches 11/11
100% Functions 3/3
100% Lines 24/24

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 691x                     1x 27x     25x 25x 25x   25x 25x   25x                 25x               25x       27x 21x   6x       32x 24x 24x 19x   5x 4x 4x       9x 4x     5x      
import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
  Logger,
} from "@nestjs/common";
import { Request, Response } from "express";
 
@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
  private readonly logger = new Logger(HttpExceptionFilter.name);
 
  catch(exception: unknown, host: ArgumentsHost): void {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
 
    const status = this.getStatus(exception);
    const message = this.getMessage(exception);
 
    const errorResponse = {
      statusCode: status,
      timestamp: new Date().toISOString(),
      path: request.url,
      method: request.method,
      message: message,
    };
 
    // Log error details
    this.logger.error(`HTTP ${status} Error: ${message}`, {
      method: request.method,
      url: request.url,
      userAgent: request.get("User-Agent"),
      ip: request.ip,
      exception: exception instanceof Error ? exception.stack : exception,
    });
 
    response.status(status).json(errorResponse);
  }
 
  private getStatus(exception: unknown): number {
    if (exception instanceof HttpException) {
      return exception.getStatus();
    }
    return HttpStatus.INTERNAL_SERVER_ERROR;
  }
 
  private getMessage(exception: unknown): string {
    if (exception instanceof HttpException) {
      const response = exception.getResponse();
      if (typeof response === "string") {
        return response;
      }
      if (typeof response === "object" && response !== null) {
        const errorResponse = response as { message?: string };
        return errorResponse.message || "Unknown error";
      }
    }
 
    if (exception instanceof Error) {
      return exception.message;
    }
 
    return "Internal server error";
  }
}