jlang
jlang

Reputation: 1057

NestJs - Send Response from Exception Filter

I'm trying to achieve a simple behavior: Whenever an exception is thrown I would like to send the error as a response. My kind of naive code looks like this, but doesn't respond at all:

Exception Filter:

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

@Catch()
export class AnyExceptionFilter implements ExceptionFilter {
  catch(exception: any, host: ArgumentsHost) {
    return JSON.stringify(
      {
        error: exception,
      },
      null,
      4,
    );
  }
}

Module

@Module({
  imports: [],
  controllers: [AppController, TestController],
  providers: [AppService, AnyExceptionFilter],
})
export class AppModule {}

main.ts

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalFilters(new AnyExceptionFilter());
  await app.listen(1212);
}
bootstrap();

Is there anything I miss? Thanks in advance :)

Upvotes: 6

Views: 8153

Answers (3)

fodisi
fodisi

Reputation: 11

Just adding a bit more info about the previous answers. The suggested code provided by @oto-meskhy here is (replicating it just for completion purposes - credits to @oto-meskhy):

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

@Catch()
export class AnyExceptionFilter implements ExceptionFilter {
  catch(error: Error, host: ArgumentsHost) {

    const response = host.switchToHttp().getResponse();

    const status = (error instanceof HttpException) ? error.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;

    response
      .status(status)
      .json(error);
  }
}

This code should work IF your NestJS application didn't defined a specific platform in the NestFactory.create() method. HoweHowever, if the chosen platform is Fastify (docs here), note that the a small piece of the code above will not work, more specifically:

    ...
    response
      .status(status)
      .send(object)

In such case, your application code should change a little bit to use Fastify's Reply methods, like this:

    // fastify
    response
      .code(status)
      .send(error);

Upvotes: 1

Oto Meskhy
Oto Meskhy

Reputation: 116

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

@Catch()
export class AnyExceptionFilter implements ExceptionFilter {
  catch(error: Error, host: ArgumentsHost) {

    const response = host.switchToHttp().getResponse();

    const status = (error instanceof HttpException) ? error.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;

    response
      .status(status)
      .json(error);
  }
}

This code seems to be working fine for me.

Nest version: 5.0.1

Upvotes: 7

VinceOPS
VinceOPS

Reputation: 2720

catch has to use the response object to send something back to the client:

const ctx = host.switchToHttp();
const response = ctx.getResponse();

response
  .status(status)
  .send('Hello');

Upvotes: 0

Related Questions