Easy to understand

[BE][Nestjs-A-02-06][공식문서로 공부하기:OVERVIEW_Exception-filters] 본문

===너의과학===/BE] Nestjs

[BE][Nestjs-A-02-06][공식문서로 공부하기:OVERVIEW_Exception-filters]

Homo knowledgian 2023. 7. 3. 23:48
728x90
반응형

=====================================================================
https://docs.nestjs.com/exception-filters
=====================================================================
[Exception filters-1]
- Nest comes with a built-in exceptions layer which is responsible for
    processing all unhandled exceptions across an application.
= Nest는 an application across(전체)에서 unhandled(처리되지 않은) exceptions을
    all(모두) processing(처리)하도록 responsible(책임을 부여)한 
    build-in exception layer를 comes with(함께 제공된다).
- 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.
= application code에서 an exception이 handled되지 않으면,
    this layer에서 it(exception)이 caught(포착)되고, 그래서 자동으로 적절한
    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).
= 즉각적으로, this action은 HttpException type(그리고 it의 subclasses)의 
    exceptions을 handles하는 built-in된 global exception filter에 의해
    performed된다.
- 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:
= an exception이 unrecognized된 경우(HttpException도 아니고 HttpException에서
    inherits{상속}하는 class도 아닌), the built-in exception이 following하는
    default JSON response를 generates한다.
- ex)
    {
        "statusCode": 500,
        "message": "Internal server error"
    }
- HINT
    The global exception filter partially supports
        the http-errors library.
    Basically, any thrown exception containing the statusCode
        and message properties will be properly populated
        and sent back as a response (instead of the default
        InternalServerErrorException for unrecognized exceptions).
= 힌트
    global exception filter는 partially http-errors library를 
        supports한다.
    기본적으로, statusCode와 message properties를 containing하는 
        any thrown(던져진) exception은 properly populated(채워)지게 되고
        response로 다시 sent될 것이다.
        (unrecognized exceptions을 대신하기 위한
            default InternalServerErrorException)
=====================================================================
[Throwing standard exceptions]
- Nest provides a built-in HttpException class, exposed from
    the @nestjs/common package.
= Nest는 @nestjs/common 패키지에서 exposed되는,
    built-in HttpException class를 provide한다.
- For typical HTTP REST/GraphQL API based applications,
    it's best practice to send standard HTTP response objects
    when certain error conditions occur.
= typical HTTP REST/GraphQL API를 based한 applications에 대해,
    certain(특정) error conditions이 occur할 때 
    standard HTTP response objects를 send하는 것이 best practice다.
- For example, in the CatsController, we have a findAll() method
    (a GET route handler).
= 예를 들어, CatsController에서, 
    findAll() method(GET route handler)가 있다.
- Let's assume that this route handler throws an exception for
    some reason.
= this route handler는 some reason로 an exception을 throws한다고
    assume(가정)하자.
- To demonstrate this, we'll hard-code it as follows:
= this(위~)를 demonstrate(시연)하기 위해, follows와 같이 hard-code할 것이다.
- ex) cats.controller.ts
    @Get()
    async findAll() {
        throw new HttpException('Forbidden', HttpStatus.FORBIDDEN);
    }
- HINT
    We used the HttpStatus here. 
    This is a helper enum imported from the @nestjs/common package.
= 힌트
    여기에 HttpStatus를 사용했다.
    This(HttpStatus)는 @nestjs/common package에서 
        imported된 helper enum이다.
- When the client calls this endpoint, the response looks like this:
= the client가 this endpoint를 calls할 때, response는 this(아래)와 같다:
    {
        "statusCode": 403,
        "message": "Forbidden"
    }
- The HttpException constructor takes two required arguments 
    which determine the response:
= HttpException constructor는 두 개의 arguments를 사용해 response를 결정한다:
    - The response argument defines the JSON response body. 
        It can be a string or an object as described below.
    = The response argument는 JSON response body를 정의한다.
        below(아래) described(설명)대로 string 또는 object가 될 수 있다.
    - The status argument defines the HTTP status code.
    = The status argument는 HTTP status code를 defines한다.
- By default, the JSON response body contains two properties:
= 기본으로, the JSON response body는 two properties를 포함한다:
    - statusCode: defaults to the HTTP status code provided 
        in the status argument
    = 상태코드: 기본값은 status argument에서 provided된 HTTP status code이다.
    - message: a short description of the HTTP error based on 
        the status
    = 메시지: the status에 based on(기반)한 HTTP error에 대한 짧은 설명
- To override just the message portion of the JSON response body, 
    supply a string in the response argument. 
= JSON response body의 message portion(부분) 만(just) override(재정의)하기
    위해서, response argument에 string을 제공해라.
- To override the entire JSON response body, 
    pass an object in the response argument. 
= entire JSON response body를 override하기 위해서,
    response argument에 object를 pass(전달)한다.
- Nest will serialize the object and return it 
    as the JSON response body.
= Nest는 object를 serialize하고 JSON response body을 return한다.
- The second constructor argument - status - should be 
    a valid HTTP status code. 
= The second constructor argument인- status -는 
    valid한 HTTP status code가 되어야 한다.
- Best practice is to use the HttpStatus enum imported 
    from @nestjs/common.
= Best practice는 @nestjs/common에서 imported된 
    HttpStatus enum을 사용하는 것이다.
- There is a third constructor argument (optional) - options - that 
    can be used to provide an error cause. 
= an error cause을 provide하는 데 사용되는 
    third constructor argument(optional)이 있다.
- 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.
= This(위~third constructor)은 response object로 serialized되지 않지만,
    logging purposes에 유용할 수 있고, be thrown(던져)진 HttpException을
    causedgks inner error에 대한 valuable information를 providing한다.
- Here's an example overriding the entire response body 
    and providing an error cause:
= error cause(원인)을 providing하고 entire response body를 overriding하는
    example이 여기 있다.
- ex) cats.controller.ts
    @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
            });
        }
    }
- Using the above, this is how the response would look:
= 위(above)예를 사용해서, this은 response가 how(어떻게) 보이는 지 표시한다:
- ex)
    {
        "status": 403,
        "error": "This is a custom message"
    }
=====================================================================
[Custom exceptions]
- In many cases, you will not need to write custom exceptions, 
    and can use the built-in Nest HTTP exception, 
    as described in the next section. 
= In many cases, custom(사용자지정) exception을 write할 필요는 없을 것이고,
    built-in Nest HTTP exception을 사용할 수 있다,
    next section에서 설멍할 것이다.
- 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. 
= customized exception을 create할 필요가 있다면, own exceptions hierarchy를
    create하는 것이 good practice이고, 거기서 your custom exceptions은
    the base HttpException class에 상속된다.
= customized exception을 create할 필요가 있다면, your custom exceptions이
    the base HttpException class에 inherit(상속)되는 own exceptions
    hierarchy를 create하는 게 good practice이다.
- With this approach, Nest will recognize your exceptions, 
    and automatically take care of the error responses. 
= this approach로, Nest는 your exceptions를 recognize하고,
    자동으로 error responses를 처리한다.
- Let's implement such a custom exception:
= 이러한 custom exception을 implement해보자.
- ex) forbidden.exception.ts
    export class ForbiddenException extends HttpException {
        constructor() {
            super('Forbidden', HttpStatus.FORBIDDEN);
        }
    }
- 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.
= ForbiddenException이 the base HttpException을 extends하기 때문에,
    built-in(기본 내장된) exception handler로 seamlessly(원활하게)
    work할 것이고, 그래서 findAll() method inside에서 
    it(ForbiddenException)을 사용할 수 있다.
- cats.controller.ts
    @Get()
    async findAll() {
        throw new ForbiddenException();
    }
=====================================================================
[Built-in HTTP exceptions]
- Nest provides a set of standard exceptions that inherit 
    from the base HttpException. 
= Nest는 base HttpException에서 inherit(상속)되는 
    a set of standard exceptions를 provides한다.
- These are exposed from the @nestjs/common package, 
    and represent many of the most common HTTP exceptions:
= These(위~)는 @nestjs/common package에 exposed되고,
    the most common HTTP exceptions를 represent(나타낸)다.
    - BadRequestException
    - UnauthorizedException
    - NotFoundException
    - ForbiddenException
    - NotAcceptableException
    - RequestTimeoutException
    - ConflictException
    - GoneException
    - HttpVersionNotSupportedException
    - PayloadTooLargeException
    - UnsupportedMediaTypeException
    - UnprocessableEntityException
    - InternalServerErrorException
    - NotImplementedException
    - ImATeapotException
    - MethodNotAllowedException
    - BadGatewayException
    - ServiceUnavailableException
    - GatewayTimeoutException
    - PreconditionFailedException
- All the built-in exceptions can also provide both an error cause 
    and an error description using the options parameter:
= All the built-in exceptions는 options parameter를 using하는
    error description과 error cause를 both provide할 수 있다.
- ex) throw new BadRequestException('Something bad happened', { cause: new Error(), description: 'Some error description' })
- Using the above, this is how the response would look:
= above(위 ex)를 사용해서, 아래와 같은 response가 표시된다.
- ex)
    {
        "message": "Something bad happened",
        "error": "Some error description",
        "statusCode": 400,
    }
=====================================================================
[Exception filters-2]
- While the base (built-in) exception filter can automatically 
    handle many cases for you, you may want full control over 
    the exceptions layer. 
= the base (built-in) exception filter가 자동적으로 many cases를
    handle할 수 있지만, the exception layer over(에 대한) full control을
    원할 수 있다.
- For example, you may want to add logging or use a different JSON 
    schema based on some dynamic factors. 
= 예를 들어, logging을 add하거나 some dynamic factors에 based on한
    different JSON schema를 사용할 수 있다.
- Exception filters are designed for exactly this purpose. 
= Exception filters는 exactly(바로) this purpose을 위해 designed(설계)되었다.
- They let you control the exact flow of control and the content of 
    the response sent back to the client.
= They(위~)는 the exact flow of control과 client로 sent back되는
    the response의 the content를 control하게 한다.
- Let's create an exception filter that is responsible for 
    catching exceptions which are an instance of the HttpException 
    class, and implementing custom response logic for them. 
= the HttpException class의 an instance인 exceptions를 catching(포착)하고,
    for them(이에 대한) custom response를 implementing하는 
    exception filter를 생성한다.
- To do this, we'll need to access the underlying platform Request 
    and Response objects. 
= this(위~)같이 하려면, underlying(기본) platform Request과 Response objects에
    access해야 할 필요가 있다.
- We'll access the Request object so we can pull out the original url 
    and include that in the logging information. 
= the Request object에 access해서 original url을 pull out(추출)하고
    logging information에 include할 수 있다.
- We'll use the Response object to take direct control of 
    the response that is sent, using the response.json() method.
= response.json() method를 using해서, is sent되는 the response을
    direct control하기 위해 Response object를 사용할 것이다.
- ex) http-exception.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,
                });
        }
    }
- HINT
    All exception filters should implement the generic 
        ExceptionFilter<T> interface. 
    This requires you to provide the catch (exception: T, 
        host: ArgumentsHost) method with its indicated signature. 
    T indicates the type of the exception.
= 힌트
    All exception filters는 the generic ExceptionFilter<T> interface를
        implement해야 한다.
    This(이렇게 하려면) indicated된 signature과 함께 
        "catch(exception: T, host: ArgumentsHost)" method를 
        provide할 필요가 있다.
    T는 the exception의 type을 indicates(나타)낸다.
- WARNING
    If you are using @nestjs/platform-fastify you can use 
        response.send() instead of response.json(). 
    Don't forget to import the correct types from fastify.
= 경고
    @nestjs/platform-fastify를 using하는 경우 response.json() 대신
        response.send()를 사용할 수 있다.
    fastify에서 correct types를 import하는 것을 잊지마라.
- The @Catch(HttpException) decorator binds the required metadata 
    to the exception filter, telling Nest that this particular filter 
    is looking for exceptions of type HttpException and nothing else.
= @Catch(HttpException) decorator는 required한 metadata를
    exception filter에 binds하여 Nest에 this particular filter가
    type HttpException and nothing else(HttpException 유형의)
    exception만 찾고 있음을 telling한다.
- The @Catch() decorator may take a single parameter, 
    or a comma-separated list. 
= The @Catch() decorator는 single parameter 또는 comma-separated list을
    사용할 수 있다.
- This lets you set up the filter for several types of exceptions 
    at once.
= This(이를 통해) at once(한번에) several types의 exception에 대한
    filter를 set up 하게 할 수 있다.
=====================================================================
[Arguments host]
- Let's look at the parameters of the catch() method. 
= catch() method의 parameters를 살펴보자.
- The exception parameter is the exception object currently 
    being processed. 
= The exception parameter는 현재 being processed(처리 중)인
    the exception object이다.
- The host parameter is an ArgumentsHost object. 
= The host parameter는 ArgumentsHost object다.
- ArgumentsHost is a powerful utility object that we'll examine 
    further in the execution context chapter*.
= ArgumentsHost는 "execution context chapter"에서 further(더) examine할
    powerful utility object이다.
- In this code sample, we use it to obtain a reference to 
    the Request and Response objects that are being passed to 
    the original request handler (in the controller where 
    the exception originates). 
= In this code sample에서, (exception이 originates할 controller에서)
    original request handler로 being passed되는 Request와 Response에 대한
    reference를 obtain(얻는) 데 사용한다.
- In this code sample, we've used some helper methods 
    on ArgumentsHost to get the desired Request and Response objects. 
= In this code sample에서, ArgumentsHost상의 some helper methods를 사용해서 
    desired(원하)는 Request와 Response objects를 얻는다.
- Learn more about ArgumentsHost here(link).
= here ArgumentsHost에 대한 자세한 내용이다.
!link : https://docs.nestjs.com/fundamentals/execution-context!
- *The reason for this level of abstraction is that ArgumentsHost 
    functions in all contexts (e.g., the HTTP server context 
    we're working with now, but also Microservices and WebSockets).
= this level의 abstraction하는 The reason은 all contexts 
    (예, 우리가 now working with하고 있는 the HTTP server context 뿐만 아니라,
    Microservices와 WebSockets)에 ArgumentsHost functions이 해당하기 때문이다.
- In the execution context chapter we'll see how we can access 
    the appropriate underlying arguments for any execution 
    context with the power of ArgumentsHost and its helper functions. 
= the execution context chapter에서 우리는 ArgumentsHost에 대한 power(권한)을
    가진 any execution context에 대해 the appropriate(적절한) 
    underlying(기본) arguments(인수)와 its(??) helper functions에 
    어떻게 access할수 있는지 see(알게)될 것이다.
- This will allow us to write generic exception filters 
    that operate across all contexts.
=====================================================================
[Binding filters]
- Let's tie our new HttpExceptionFilter to the CatsController's 
    create() method.
= new HttpExceptionFilter을 CatsController의 create() method에
    tie(연결)합시다.
- ex) cats.controller.ts
    @Post()
    @UseFilters(new HttpExceptionFilter())
    async create(@Body() createCatDto: CreateCatDto) {
        throw new ForbiddenException();
    }
- HINT
    The @UseFilters() decorator is imported 
        from the @nestjs/common package.        
= 힌트
    @UseFilter() decorator를 @nestjs/common package에서 가져온다.
- We have used the @UseFilters() decorator here. 
= here에서 @UseFilters() decorator를 사용했다.
- Similar to the @Catch() decorator, it can take a single filter 
    instance, or a comma-separated list of filter instances. 
= @Catch() decorator와 마찬가지로, a single filter instance 또는 
    comma-separated(쉼표로 구분된) list of filter instances를 사용할 수 있다.
- Here, we created the instance of HttpExceptionFilter in place.
= Here, in place의 HttpExceptionFilter의 instance를 만들었다.
- Alternatively, you may pass the class (instead of an instance), 
    leaving responsibility for instantiation to the framework, 
    and enabling dependency injection.
= Alternatively(대안으로), (an instance 대신) class를 pass하고 
    instantiation에 대한 responsibility(책임)은 framework에 leaving하고,
    dependency injection을 enabling(활성화)할 수 있다.
- ex) cats.controller.ts
    @Post()
    @UseFilters(HttpExceptionFilter)
    async create(@Body() createCatDto: CreateCatDto) {
        throw new ForbiddenException();
    }
- HINT
    Prefer applying filters by using classes instead of instances 
        when possible. 
    It reduces memory usage since Nest can easily reuse instances of 
        the same class across your entire module.
= 힌트
    when possible한 instances(경우) 대신에 classes를 사용해서 filters를
        applying하는게 좋다.
    Nest는 your entire module에서 the same class의 instances를
        easily(쉽게) reuse할 수 있어서 memory usage이 reduces한다.
- In the example above, the HttpExceptionFilter is applied only 
    to the single create() route handler, making it method-scoped.
= 위 예제에서, the HttpExceptionFilter는 the single create() route
    handler에만 applied되고, method-scoped가 생성된다.
- Exception filters can be scoped at different levels: 
    method-scoped, controller-scoped, or global-scoped.
= Exception filters는 method-scoped, controller-scoped, 
    또는 global-scoped와 같은 different levels에서 be scoped될 수 있다.
- For example, to set up a filter as controller-scoped, 
    you would do the following:
= 예를 들어, filter를 controller-scoped로 set up하려면,
    the following을 수행한다.
- ex) cats.controller.ts
    @UseFilters(new HttpExceptionFilter())
    export class CatsController {}
- This construction sets up the HttpExceptionFilter 
    for every route handler defined inside the CatsController.
= This construction(구성)은 CatsController에 defined된
    every route handler에 대해 sets up한다.
- To create a global-scoped filter, you would do the following:
= global-scoped filter를 create하려면, following을 수행한다.
- ex) main.ts
    async function bootstrap() {
        const app = await NestFactory.create(AppModule);
        app.useGlobalFilters(new HttpExceptionFilter());
        await app.listen(3000);
    }
    bootstrap();
- WARNING
    The useGlobalFilters() method does not set up filters 
        for gateways or hybrid applications.
= 경고
    useGlobalFilters() method는 gateways 또는 hybrid applications에 대한
        filters를 set up하지 않는다.
- Global-scoped filters are used across the whole application, 
    for every controller and every route handler. 
= Global-scoped filters는 every controller와 every route handler에 대해,
    the whole application에 across되어 are used된다.
- In terms of dependency injection, global filters registered 
    from outside of any module (with useGlobalFilters() 
    as in the example above) cannot inject dependencies 
    since this is done outside the context of any module. 
= dependency injection 측면에서, (위 예제에서처럼 useGlobalFilters()로 된)
    any module의 outside에서 registered된 global filters는 any module의
    context outside(외부에서) is done(수행되기) 때문에 dependencies를
    inject할 수 없다.
- In order to solve this issue, you can register a global-scoped 
    filter directly from any module using the following construction:
= this issue를 solve하기 위해서, following construction을 using해서
    any module에서 directly global-scoped filter를 register할 수 있다.
- ex) app.module.ts
    import { Module } from '@nestjs/common';
    import { APP_FILTER } from '@nestjs/core';

    @Module({
        providers: [
            {
                provide: APP_FILTER,
                useClass: HttpExceptionFilter,
            },
        ],
    })
    export class AppModule {}
- HINT
    When using this approach to perform dependency injection for 
        the filter, note that regardless of the module where 
        this construction is employed, the filter is, in fact, global. 
    Where should this be done? 
    Choose the module where the filter 
        (HttpExceptionFilter in the example above) is defined. 
    Also, useClass is not the only way of dealing with 
        custom provider registration. 
    Learn more here.
= 힌트
    this approach을 using하여 the filter에 대한 dependency injection을
        perform할때, this construction(구조)가 is employed(사용)되는
        the module과 무관하게, the filter는, 실제로, global이라는 점을
        note(유의)하라.
    Where에서 this(위~?)이 써야하나?
    filter(HttpExceptionFilter는 위 example에서)가 defined된
        module을 선택한다.
    또한, useClass는 custom provider registration을 dealing with하는
        only way가 아니다.
    here(link)에서 더 알아보라.
!link : https://docs.nestjs.com/fundamentals/custom-providers!
- You can add as many filters with this technique as needed; 
    simply add each to the providers array.
= this technique으로 as needed한 만큼 many filters를 add 할 수 있다;
    단순히 providers array를 add하면 된다.
=====================================================================
[Catch everything]
- In order to catch every unhandled exception (regardless of 
    the exception type), leave the @Catch() decorator's parameter 
    list empty, e.g., @Catch().
= every unhandled exception을 catch하기 위해서(the exceptin type과 무관하게)
    the @Catch() decorator's의 parameter list를 empty로 leave(남겨)둔다,
    예, @Catch().
- In the example below we have a code that is platform-agnostic 
    because it uses the HTTP adapter to deliver the response, 
    and doesn't use any of the platform-specific objects 
    (Request and Response) directly:
= below example에서 the HTTP adapter를 uses해서 response를 deliver하고 
    platform-specific objects(Request & Response)를 directly(직접)
    use하지 않기 때문에 platform-agnostic(구애받지 않은) code가 있다.
- ex)
    import {
        ExceptionFilter,
        Catch,
        ArgumentsHost,
        HttpException,
        HttpStatus,
    } from '@nestjs/common';
    import { HttpAdapterHost } from '@nestjs/core';

    @Catch()
    export class AllExceptionsFilter implements ExceptionFilter {
        constructor(private readonly httpAdapterHost: HttpAdapterHost) {}

        catch(exception: unknown, host: ArgumentsHost): void {
            // In certain situations `httpAdapter` might not be available in the
            // constructor method, thus we should resolve it here.
            const { httpAdapter } = this.httpAdapterHost;

            const ctx = host.switchToHttp();

            const httpStatus =
                exception instanceof HttpException
                ? exception.getStatus()
                : HttpStatus.INTERNAL_SERVER_ERROR;

            const responseBody = {
                statusCode: httpStatus,
                timestamp: new Date().toISOString(),
                path: httpAdapter.getRequestUrl(ctx.getRequest()),
            };

            httpAdapter.reply(ctx.getResponse(), responseBody, httpStatus)                                                                                                                                                                                                                         ;
        }
    }
- WARNING
    When combining an exception filter that catches everything 
        with a filter that is bound to a specific type, 
        the "Catch anything" filter should be declared first 
        to allow the specific filter to correctly handle the bound type.
= 경고
    everything을 catches하는 exception filter를 specific type에 bound된
        filter와 combining(결합)할 때, specific filter가 bound type을
        correctly handle하도록 "Catch anything" filter를 
        first declared해야 한다.
=====================================================================
[Inheritance]
- Typically, you'll create fully customized exception filters 
    crafted to fulfill your application requirements. 
= 일반적으로, your application requirements을 fulfill(충족)하도록
    crafted(제작)된 fully customized된 exception filters를 만든다.
- However, there might be use-cases when you would like to simply 
    extend the built-in default global exception filter, 
    and override the behavior based on certain factors.
= 그러나, the built-in된 default global exception filter를 
    simply extend하고 certain factors에 based on하여 behavior를
    override(재정의)하려는 use-cases가 있을 수 있다.
- In order to delegate exception processing to the base filter, 
    you need to extend BaseExceptionFilter and call the inherited 
    catch() method.
= the base filter에 exception processing을 delegate(위임)하려면,
    inherited(상속된) catch() method를 call하고 BaseExceptionFilter를
    extend할 필요가 있다.
- ex) all-exceptions.filter.ts
    import { Catch, ArgumentsHost } from '@nestjs/common';
    import { BaseExceptionFilter } from '@nestjs/core';

    @Catch()
    export class AllExceptionsFilter extends BaseExceptionFilter {
        catch(exception: unknown, host: ArgumentsHost) {
            super.catch(exception, host);
        }
    }
- WARNING
    Method-scoped and Controller-scoped filters that extend the 
        BaseExceptionFilter should not be instantiated with new. 
    Instead, let the framework instantiate them automatically.
= 경고
    BaseExceptionFilter를 extend한 Method-scoped와 
        Controller-scoped filter는 new로 instantiated화 해서는 안된다.
    대신, framework가 자동적으로 them(위 두개)를 instantiate하게 해야 한다.
- The above implementation is just a shell demonstrating the approach. 
= above implementation은 the approach를 demonstrating하는 shell일 뿐이다.
- Your implementation of the extended exception filter would include 
    your tailored business logic (e.g., handling various conditions).
= the extended된 exception filter의 implementation은 tailored(맞춤형)의
    business logic을 포함한다.(예, various conditions를 처리)
- Global filters can extend the base filter. 
= Global filter는 base filter를 extend할 수 있다.
- This can be done in either of two ways.
= This(위~)은 two ways 중 하나로 수행될 수 있다.
- The first method is to inject the HttpAdapter reference 
    when instantiating the custom global filter:
= The first method는 the custom global filter를 instantiating할 때
    the HttpAdapter reference를 inject하는 것이다:
- ex)
    async function bootstrap() {
        const app = await NestFactory.create(AppModule);

        const { httpAdapter } = app.get(HttpAdapterHost);
        app.useGlobalFilters(new AllExceptionsFilter(httpAdapter));

        await app.listen(3000);
    }
    bootstrap();
- The second method is to use the APP_FILTER token as shown here.
= The second method는 here(link)에 shown된 APP_FILTER tokens을
    사용하는 것이다.
!link : https://docs.nestjs.com/support!
=====================================================================

https://github.com/yigongyikong/nestjs_official_docs/blob/officialDocs/docs.nestjs.com/02_06_OVERVIEW_Exception-filters.txt

 

[P.S. 잘못된 부분이나 이해하기 어려운 부분이 있다면, 댓글 남겨주시기 바랍니다.]

반응형
Comments