ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Exception Filters
    Node.js/Nest 2023. 10. 30. 16:52

    Nest.js의 Exception Filters에 대해 정리하였습니다.


     


    < Exception Filters >

    Nest comes with a built-in exceptions layer which is responsible for processing all unhandled exceptions across an application. When an exception is not handled by your application code, it is caught by this layer, which then automatically sends an appropriate user-friendly response.

     

    Out of the box, this action is performed by a built-in global exception filter, which handles exceptions of type HttpException (and subclasses of it). When an exception is unrecognized (is neither  HttpException  nor a class that inherits from  HttpException ), the built-in exception filter generates the following default JSON response:

    {
      "statusCode": 500,
      "message": "Internal server error"
    }

     

     


    < Http Exception (Standard Exception) >

    For typical HTTP REST/GraphQL API based applications, it's best practice to send standard HTTP response objects when certain error conditions occur.

     

     

    The HttpException constructor takes two required arguments and one optional argument which determine the response:

    • The  response  argument defines the JSON response body. It can be a string or an object as described below.
    • The  status  argument defines the HTTP status code.
    • The  optional  that can be used to provide an error cause. This  cause  object is not serialized into the response object, but it can be useful for logging purposes, providing valuable information about the inner error that caused the  HttpException  to be thrown.

     

    Ex)

    @Get()
    async findAll() {
      try {
        await this.service.findAll()
      } catch (error) { 
        throw new HttpException({
          status: HttpStatus.FORBIDDEN,
          error: 'This is a custom message',
        }, HttpStatus.FORBIDDEN, {
          cause: error
        });
      }
    }

     

    response would like :

    {
      "status": 403,
      "error": "This is a custom message"
    }

     

     


    < Custom Exceptions >

    If you do need to create customized exceptions, it's good practice to create your own exceptions hierarchy, where your custom exceptions inherit from the base HttpException class

     

    Ex)

    export class ForbiddenException extends HttpException {
      constructor() {
        super('Forbidden', HttpStatus.FORBIDDEN);
      }
    }
    @Get()
    async findAll() {
      throw new ForbiddenException();
    }

    Since ForbiddenException extends the base HttpException, it will work seamlessly with the built-in exception handler, and therefore we can use it inside the findAll( ) method.

     

     


    < Built-in HTTP exceptions >

    Nest provides a set of standard exceptions that inherit from the base HttpException These are exposed from the @nestjs/common package

     

     

    •  BadRequestException 
    •  UnauthorizedException 
    •  NotFoundException 
    •  ForbiddenException 
    •  NotAcceptableException 
    •  RequestTimeoutException 
    •  ConflictException 
    •  GoneException 
    •  HttpVersionNotSupportedException 
    •  PayloadTooLargeException 
    •  UnsupportedMediaTypeException 
    •  UnprocessableEntityException 
    •  InternalServerErrorException 
    •  NotImplementedException 
    •  ImATeapotException 
    •  MethodNotAllowedException 
    •  BadGatewayException 
    •  ServiceUnavailableException 
    •  GatewayTimeoutException 
    •  PreconditionFailedException 

     

    Ex) All the built-in exceptions can also provide both an error cause and an error description using the options parameter:

    throw new BadRequestException('Something bad happened', { cause: new Error(), description: 'Some error description' })

     

    response would like :

    {
      "message": "Something bad happened",
      "error": "Some error description",
      "statusCode": 400,
    }

     

     

     


     

    Reference : https://docs.nestjs.com/exception-filters

     

    Documentation | NestJS - A progressive Node.js framework

    Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Rea

    docs.nestjs.com

     

     

    'Node.js > Nest' 카테고리의 다른 글

    Guards  (0) 2023.11.21
    Pipes  (0) 2023.11.13
    Middlewares  (0) 2023.10.18
    Modules  (0) 2023.09.26
    Providers  (0) 2023.09.08

    댓글

Designed by Tistory.