NestJS 系列教程(四):中间件、中断器与异常过滤器详解
🔄 NestJS 系列教程(四):中间件、中断器与异常过滤器详解
✨ 本篇目标
你将学会:
- 什么是中间件(Middleware),如何拦截请求
- 什么是异常过滤器(Exception Filters),如何统一处理错误
- Nest 中的请求生命周期是怎样的
- 编写全局/模块级中间件与异常处理器
🚦 1. 中间件(Middleware)
什么是中间件?
中间件是一个在请求到达处理函数之前被调用的函数。你可以用它来记录日志、验证请求、添加请求数据等。
中间件的特征:
- 类似 Express 的中间件函数
(req, res, next)
- 可以访问请求与响应对象
- 必须手动调用
next()
才会进入下一个处理阶段
🛠️ 编写中间件
示例:日志中间件 logger.middleware.ts
在 src/common/middleware/logger.middleware.ts
文件中创建:
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';@Injectable()
export class LoggerMiddleware implements NestMiddleware {use(req: Request, res: Response, next: NextFunction) {console.log(`[Request] ${req.method} ${req.originalUrl}`);next();}
}
🔧 应用中间件(模块级注册)
在 cats.module.ts
中添加:
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { CatsController } from './cats.controller';
import { CatsService } from './cats.service';
import { LoggerMiddleware } from '../common/middleware/logger.middleware';@Module({controllers: [CatsController],providers: [CatsService],
})
export class CatsModule implements NestModule {configure(consumer: MiddlewareConsumer) {consumer.apply(LoggerMiddleware).forRoutes('cats'); // 仅拦截 /cats 路由}
}
可以通过
.forRoutes()
控制中间件作用范围,如所有 GET 路由、指定控制器、指定路径等。
🧨 2. 异常过滤器(Exception Filters)
默认行为
Nest 默认抛出的异常会被自动转化为 JSON 格式:
{"statusCode": 400,"message": "some error","error": "Bad Request"
}
但你可以创建自定义异常处理逻辑。
编写自定义异常过滤器
创建 common/filters/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();const errorResponse = {success: false,timestamp: new Date().toISOString(),path: request.url,message: exception.message,};response.status(status).json(errorResponse);}
}
✍️ 应用异常过滤器
方法级
@Post()
@UseFilters(HttpExceptionFilter)
create(@Body() dto: CreateCatDto) {throw new BadRequestException('手动抛出异常示例');
}
控制器级
@UseFilters(HttpExceptionFilter)
@Controller('cats')
export class CatsController {}
全局注册(推荐)
在 main.ts
中添加:
import { HttpExceptionFilter } from './common/filters/http-exception.filter';async function bootstrap() {const app = await NestFactory.create(AppModule);app.useGlobalFilters(new HttpExceptionFilter());await app.listen(3000);
}
🔁 3. Nest 请求生命周期简图
一个请求在 Nest 应用中经历以下流程:
客户端请求↓
中间件 (Middleware)↓
守卫 (Guards)↓
拦截器 (Interceptors)↓
管道 (Pipes)↓
控制器方法 (Controller)↓
服务 (Service)↑
异常过滤器 (ExceptionFilter)(如有异常)↑
响应客户端
本章主要关注中间件与异常过滤器,后续我们将逐步引入守卫、拦截器、管道的深入使用。
✅ 本篇小结
本章我们学习了:
- 如何编写并应用 Nest 的中间件(Logger)
- 理解并实现异常过滤器(统一错误响应格式)
- 掌握 Nest 请求生命周期的关键阶段
🔮 下一篇预告
第5篇:守卫(Guards)与认证逻辑实现(基于角色与 JWT)
下一篇将介绍如何使用 Guards 实现路由级权限控制、角色限制、以及 JWT 用户验证机制。