Nest: How to customise Nest default error handler?

Created on 26 Sep 2017  路  4Comments  路  Source: nestjs/nest

Example: throw new Error('Boom');

All I get for response is the following:

{
    "statusCode": 500,
    "message": "Internal server error"
}
  • What if i want to print the stack trace too in the above response while in development?
  • How would I do that?

In express we have this

app.use(function (err, req, res, next) {
  // logic
})

What about nest?

I read the docs, but it only catches http errors.

Most helpful comment

Here is an example which catches any error, and renders templates for certain errors.
By the way, as of nest 5.0.0, the 2nd param for the catch method is an ArgumentsHost object, which encapsulates the response object.

# errors.filter.ts
import { ExceptionFilter, Catch, HttpException, ArgumentsHost, HttpStatus } from '@nestjs/common';

@Catch()
export class ErrorFilter implements ExceptionFilter {
  catch(error: Error, host: ArgumentsHost) {
    let response = host.switchToHttp().getResponse();
    let status = (error instanceof HttpException) ? error.getStatus(): HttpStatus.INTERNAL_SERVER_ERROR;

    if (status === HttpStatus.UNAUTHORIZED) 
        return response.status(status).render('views/401');
    if (status === HttpStatus.NOT_FOUND) 
        return response.status(status).render('views/404');
    if (status === HttpStatus.INTERNAL_SERVER_ERROR) {
        if (process.env.NODE_ENV === 'production') {
          console.error(error.stack);
          return response.status(status).render('views/500');
        }
        else {
          let message = error.stack;
          return response.status(status).send(message); 
        } 
    }
  }
}
# main.ts
import { NestFactory } from '@nestjs/core';
import { ApplicationModule } from './app.module';
import { ErrorFilter } from './app/errors/error.filter';

async function bootstrap() {
  const app = await NestFactory.create(ApplicationModule);

  app.useStaticAssets(__dirname + '/public');
  app.setBaseViewsDir(__dirname + '/views');
  app.setViewEngine('ejs');
  app.useGlobalFilters(new ErrorFilter())

  await app.listen(3000);
}
bootstrap();

All 4 comments

I see, thanks.

Here is an example which catches any error, and renders templates for certain errors.
By the way, as of nest 5.0.0, the 2nd param for the catch method is an ArgumentsHost object, which encapsulates the response object.

# errors.filter.ts
import { ExceptionFilter, Catch, HttpException, ArgumentsHost, HttpStatus } from '@nestjs/common';

@Catch()
export class ErrorFilter implements ExceptionFilter {
  catch(error: Error, host: ArgumentsHost) {
    let response = host.switchToHttp().getResponse();
    let status = (error instanceof HttpException) ? error.getStatus(): HttpStatus.INTERNAL_SERVER_ERROR;

    if (status === HttpStatus.UNAUTHORIZED) 
        return response.status(status).render('views/401');
    if (status === HttpStatus.NOT_FOUND) 
        return response.status(status).render('views/404');
    if (status === HttpStatus.INTERNAL_SERVER_ERROR) {
        if (process.env.NODE_ENV === 'production') {
          console.error(error.stack);
          return response.status(status).render('views/500');
        }
        else {
          let message = error.stack;
          return response.status(status).send(message); 
        } 
    }
  }
}
# main.ts
import { NestFactory } from '@nestjs/core';
import { ApplicationModule } from './app.module';
import { ErrorFilter } from './app/errors/error.filter';

async function bootstrap() {
  const app = await NestFactory.create(ApplicationModule);

  app.useStaticAssets(__dirname + '/public');
  app.setBaseViewsDir(__dirname + '/views');
  app.setViewEngine('ejs');
  app.useGlobalFilters(new ErrorFilter())

  await app.listen(3000);
}
bootstrap();

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

FranciZ picture FranciZ  路  3Comments

thohoh picture thohoh  路  3Comments

menme95 picture menme95  路  3Comments

rlesniak picture rlesniak  路  3Comments

anyx picture anyx  路  3Comments