NestJS 有一个内置异常层,它自动捕获未处理的错误并将其转换为适当的 HTTP 响应。你通过抛出异常(通常是内置 HTTP 异常类)来表示错误,Nest 会将其格式化为包含正确状态代码的结构化 JSON 响应。
抛出内置 HTTP 异常
ts
{ , , } ;
()
() {
user = ..(id);
(!user) {
();
}
user;
}
NestJS 提供映射到 HTTP 状态代码的异常类,抛出一个会自动生成正确、结构化的响应:
{ "statusCode": 404, "message": "User not found", "error": "Not Found" }
BadRequestException → 400
UnauthorizedException → 401
ForbiddenException → 403
NotFoundException → 404
ConflictException → 409
UnprocessableEntityException → 422
InternalServerErrorException → 500
每个常见的 HTTP 错误都有一个对应的类 — 使用适当的类来传达正确的状态。
// custom status + body via the base HttpException
throw new HttpException(
{ status: HttpStatus.FORBIDDEN, error: "custom message" },
HttpStatus.FORBIDDEN,
);
export class UserNotFoundException extends NotFoundException {
constructor(id: string) {
super(`User with id ${id} not found`); // domain-specific, reusable
}
}
throw new UserNotFoundException(id);
If code throws a non-HttpException error (e.g. a plain Error or an unexpected
exception), NestJS's default exception filter catches it and returns a generic
500 Internal Server Error (without leaking internal details to the client).
// a custom exception filter customizes how errors are formatted/logged globally
@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
catch(exception: unknown, host: ArgumentsHost) {
// log, format the response, etc.
}
}
app.useGlobalFilters(new AllExceptionsFilter()); // apply app-wide
为了实现一致的错误格式化、日志记录或处理非 HTTP 错误,你可以使用异常过滤器(一个相关的、更高级的功能)。
适当的异常处理对于构建可靠的 API 至关重要,NestJS 的内置异常层使其干净而一致。
理解如何抛出 HTTP 异常(NotFoundException、BadRequestException 等)是日常知识 — 这是用正确的状态代码和结构化、客户端友好的 JSON 响应来表示错误的惯用方式,无需在每个处理程序中手动构造错误响应。
框架会自动捕获这些异常并对其进行格式化,并且会安全地将意外错误转换为通用 500 而不会泄露内部细节(对安全性很重要)。
了解常见的异常类、如何抛出自定义消息/异常,以及异常过滤器存在用于全局自定义(一致的格式化、日志记录)是构建健壮、专业 NestJS API 的基础。
干净、一致的错误处理是高质量后端代码的标志,使其成为框架的核心、频繁使用的方面。