簡體   English   中英

什么是 Nestjs 錯誤處理方法(業務邏輯錯誤與 http 錯誤)?

[英]What is the nestjs error handling approach (business logic error vs. http error)?

在使用 NestJS 創建 API 時,我想知道哪種是處理錯誤/異常的最佳方式。 我發現了兩種不同的方法:

  1. 讓單個服務和驗證管道throw new Error() ,讓控制器catch它們,然后拋出適當類型的HttpExceptionBadRequestExceptionForbiddenException等。)
  2. 讓控制器簡單地調用負責處理該部分業務邏輯的服務/驗證管道方法,並拋出適當的HttpException

這兩種方法各有利弊:

  1. 這似乎是正確的方法,但是,服務可能會因不同的原因返回Error ,我如何從控制器知道哪個是相應類型的HttpException返回?
  2. 非常靈活,但在服務中使用Http相關的東西似乎是錯誤的。

我想知道,哪一種(如果有的話)是“嵌套 js”的做法?

你怎么處理這件事?

假設您的業務邏輯拋出EntityNotFoundError並且您希望將其映射到NotFoundException

為此,您可以創建一個Interceptor來轉換您的錯誤:

@Injectable()
export class NotFoundInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    // next.handle() is an Observable of the controller's result value
    return next.handle()
      .pipe(catchError(error => {
        if (error instanceof EntityNotFoundError) {
          throw new NotFoundException(error.message);
        } else {
          throw error;
        }
      }));
  }
}

然后,您可以通過將@UseInterceptors(NotFoundInterceptor)添加到控制器的類或方法中來使用它; 甚至作為所有路由的全局攔截器。 當然,您也可以在一個攔截器中映射多個錯誤。

在這個codeandbox 中嘗試一下。

您可能不僅希望將服務綁定到 HTTP 接口,還希望綁定到 GraphQL 或任何其他接口。 因此最好將業務邏輯級別的異常從服務轉換為控制器中的 Http 級別異常(BadRequestException、ForbiddenException)。

以最簡單的方式,它看起來像

import { BadRequestException, Injectable } from '@nestjs/common';

@Injectable()
export class HttpHelperService {
  async transformExceptions(action: Promise<any>): Promise<any> {
    try {
      return await action;
    } catch (error) {
      if (error.name === 'QueryFailedError') {
        if (/^duplicate key value violates unique constraint/.test(error.message)) {
          throw new BadRequestException(error.detail);
        } else if (/violates foreign key constraint/.test(error.message)) {
          throw new BadRequestException(error.detail);
        } else {
          throw error;
        }
      } else {
        throw error;
      }
    }
  }
}

進而

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM