[NestJs] Introduction to NestJs Error Handling & Expection filter

Throw expection from Controller:

  @Put(':courseId')
  async updateCourse(
    @Param('courseId') courseId: string,
    @Body() changes: Partial<Course>,
  ): Promise<Course> {
    if (changes._id) {
      throw new BadRequestException('Cannot update course id');
    }

    return this.couresDB.updateCourse(courseId, changes);
  }

Expection types: https://docs.nestjs.com/exception-filters#built-in-http-exceptions

 

We can create global reuseable expection filters:

src/filters/http-expections.filter.ts:

import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
} from '@nestjs/common';
import { Request, Response } from 'express';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    const status = exception.getStatus();

    response.status(status).json({
      statusCode: status,
      timestamp: new Date().toISOString(),
      path: request.url,
      createdBy: 'HttpExceptionFilter',
      errorMessage: exception.message.message,
    });
  }
}

 

Using it for one single HTTP request:

  @Put(':courseId')
  @UseFilters(new HttpExceptionFilter())
  async updateCourse(
    @Param('courseId') courseId: string,
    @Body() changes: Partial<Course>,
  ): Promise<Course> {
    if (changes._id) {
      throw new BadRequestException('Cannot update course id');
    }

    return this.couresDB.updateCourse(courseId, changes);
  }

 

Using it for one controller's all HTTP Requests:

@Controller('courses')
@UseFilters(new HttpExceptionFilter())
export class CoursesController {

 

Using it for all global requests:

main.ts:

import { NestFactory } from '@nestjs/core';

import { AppModule } from './app.module';
import { HttpExceptionFilter } from './filters/http-exception.filter';

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

  app.setGlobalPrefix('api');
  app.useGlobalFilters(new HttpExceptionFilter());

  await app.listen(9000);
}

bootstrap();

 

posted @ 2020-01-13 14:28  Zhentiw  阅读(443)  评论(0)    收藏  举报