Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :)

like image 547
jlang Avatar asked Jun 13 '18 07:06

jlang


2 Answers

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

like image 181
Oto Meskhy Avatar answered Oct 20 '22 01:10

Oto Meskhy


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);
like image 29
fodisi Avatar answered Oct 20 '22 01:10

fodisi