[英]What is the nestjs error handling approach (business logic error vs. http error)?
在使用 NestJS 創建 API 時,我想知道哪種是處理錯誤/異常的最佳方式。 我發現了兩種不同的方法:
throw new Error()
,讓控制器catch
它們,然后拋出適當類型的HttpException
( BadRequestException
、 ForbiddenException
等。)HttpException
。這兩種方法各有利弊:
Error
,我如何從控制器知道哪個是相應類型的HttpException
返回?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.