Nestjs TypeError: Converting circular structure to JSON

56 Views Asked by At

Everything works fine when throwing exceptions using:

throw new Error("...") 

The problem: when throwing exceptions using a customize httpexception such as

throw new UnauthorizedException("...")

nestjs exception filter crash when processing this final line:

httpAdapter.reply(ctx.getResponse(), resBody);

This is the code for the exceptionFiler.ts file:

import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
} from '@nestjs/common';
import { HttpAdapterHost } from '@nestjs/core';

export interface HttpExceptionResponse {
  statusCode: number;
  message: string;
  error: string;
}
@Catch()
export class AllExceptionFilter implements ExceptionFilter {
  constructor(private readonly httpAdapterHost: HttpAdapterHost) {}

  catch(exception: HttpException, host: ArgumentsHost) {
    const { httpAdapter } = this.httpAdapterHost;
    const ctx = host.switchToHttp();
    const response =
      exception instanceof HttpException
        ? ctx.getResponse<Response>()
        : String(exception);

    const resBody = {
      // statusCode: status,
      timestamp: new Date().toISOString(),
      path: httpAdapter.getRequestUrl(ctx.getRequest()),
      message: response || 'Something went wrong',
      errorResponse: response,
    };

    //issue here! converting curcular structure to JSON
    httpAdapter.reply(ctx.getResponse(), resBody);
  }
}
0

There are 0 best solutions below