All files / src/common/filters all-exceptions.filter.ts

0% Statements 0/13
0% Branches 0/14
0% Functions 0/2
0% Lines 0/11

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                                                                             
import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { HttpAdapterHost } from '@nestjs/core';
 
@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  constructor(private readonly httpAdapterHost: HttpAdapterHost) {}
 
  catch(exception: unknown, host: ArgumentsHost): void {
    const { httpAdapter } = this.httpAdapterHost;
 
    const ctx = host.switchToHttp();
 
    const httpStatus =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;
 
    const base = exception as any;
    const message = exception instanceof HttpException
      ? (exception.getResponse() as any)?.message || exception.message
      : (typeof base?.message === 'string' ? base.message : 'Internal Server Error');
 
    const responseBody = {
      statusCode: httpStatus,
      message,
      error: exception instanceof HttpException ? exception.name : 'InternalServerError',
      timestamp: new Date().toISOString(),
      path: httpAdapter.getRequestUrl(ctx.getRequest()),
    };
 
    httpAdapter.reply(ctx.getResponse(), responseBody, httpStatus);
  }
}