如何在 NestJS 中处理异常?

NestJS 提供了强大的异常处理机制。可以通过 @Catch() 装饰器创建自定义异常过滤器来捕获和处理异常。例如:

typescript复制代码

typescript 复制代码
import { ExceptionFilter, Catch, ArgumentsHost, HttpException, HttpStatus } 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,
      message: exception.message,
    });
  }
}

在模块中全局注册异常过滤器:

typescript复制代码

python 复制代码
import { Module, APP_FILTER } from '@nestjs/common';
import { APP_INTERCEPTOR } from '@nestjs/core';
import { HttpExceptionFilter } from './http-exception.filter';

@Module({
  providers: [
    {
      provide: APP_FILTER,
      useClass: HttpExceptionFilter,
    },
  ],
})
export class AppModule {}

这样,所有未捕获的 HttpException 都会被 HttpExceptionFilter 处理,返回统一的错误响应格式。

相关推荐
Aotman_2 分钟前
Vue el-table 字段自定义排序(进阶)
前端·javascript·vue.js·elementui·前端框架·ecmascript
Charonrise2 分钟前
完美解决Microsft Edge浏览器双击无法打开 双击无反应 无响应 不能用
前端·edge
华仔啊4 分钟前
这 5 个冷门 HTML 标签,让我直接删了100 行 JS 代码!
前端·html
西维8 分钟前
大屏、看板必备的丝滑技巧 — 数字滚动
前端·javascript·动效
前端工作日常12 分钟前
我学习到的AG-UI的功能:全面的交互支持
前端
LawrenceLan13 分钟前
Flutter 零基础入门(十三):late 关键字与延迟初始化
开发语言·前端·flutter·dart
深耕AI13 分钟前
【wordpress系列教程】03 网站页面的编辑
开发语言·前端
前端达人20 分钟前
2026年React数据获取的第六层:从自己写缓存到用React Query——减少100行代码的秘诀
前端·javascript·react.js·缓存·前端框架
小酒星小杜23 分钟前
在AI时代,技术人应该每天都要花两小时来构建一个反内耗构建系统 - Ship 篇
前端·javascript·vue.js