上一篇:NestJS 入门(3):Guard 如何挡住未登录请求? 讲了鉴权门槛。
业务代码里常见这样写:
throw new UnauthorizedException('Invalid credentials');
但前端拿到的往往不是 Nest 默认的异常结构,而是统一信封,例如:
{
"code": 1001,
"msg": "Invalid credentials",
"data": null
}
成功时则是:
{
"code": 0,
"msg": "success",
"data": {
/* 业务数据 */
}
}
这篇文章只讲清楚一件事:
Interceptor 负责成功包装,Exception Filter 负责失败整形——两边约定同一套信封,前端才能稳定解析。
1. 为什么要统一信封?
如果每个接口自己返回:
{ "ok": true, "result": ... }
{ "success": 1, "payload": ... }
{ "error": "xxx" }
前端就要写一堆特殊判断。统一成:
| 字段 | 含义 |
|---|---|
code | 业务错误码;0 表示成功 |
msg | 给人看的说明 |
data | 成功时的业务数据;失败常为 null |
前端只需:
if (data.code === 0) {
return data.data;
}
// 否则按 data.code / data.msg 提示用户
HTTP 状态码仍然有用(401/403/404),但业务语义优先看 code。
例如同是 401,可以细分成「未登录 / token 无效 / 凭证错误」。
2. 成功路径:全局 Response Interceptor
Nest 启动时挂上全局拦截器:
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalInterceptors(new ResponseInterceptor());
app.useGlobalFilters(new HttpExceptionFilter());
await app.listen(3000);
}
拦截器大致是这样:
@Injectable()
export class ResponseInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
const req = context.switchToHttp().getRequest();
if (this.shouldSkip(req)) {
return next.handle(); // SSE / 文件下载不要包
}
return next.handle().pipe(
map((data) => ({
code: 0,
msg: 'success',
data: data ?? null,
}))
);
}
private shouldSkip(req: { path?: string; url?: string }): boolean {
const path = req.path || req.url || '';
// 按路径约定跳过。不要在 intercept() 开头读 Content-Type:
// 那时 Handler 往往还没 writeHead,头是空的,跳过会失效。
return (
path.includes('/stream') ||
path.includes('/generate') ||
path.includes('/optimize/')
);
}
}
Controller 仍然可以「直接 return 业务对象」:
@Get()
findAll() {
return this.projectsService.findAll(userId);
// 实际响应会被包成 { code: 0, msg: 'success', data: [...] }
}
你不用在每个方法里手写信封。
为什么 SSE 要跳过?
SSE 要持续写:
data: {"event":"content","data":"你好"}\n\n
如果也走成功拦截器,可能被一次性包成 JSON 信封,流就坏了。
所以这类接口在拦截器里直接 next.handle(),不做 map。
判断不要赌响应头:intercept() 运行时,Controller 里的 res.writeHead 通常还没执行。更稳的是:
- 按路径前缀跳过(上面那样)
- 或自定义装饰器
SetMetadata('skipEnvelope', true),拦截器读 metadata - SSE 本身用
@Res()接管原生响应,本来也不该再走 JSON 包装
3. 失败路径:全局 Exception Filter
业务里抛 Nest 自带异常也可以:
throw new UnauthorizedException('Invalid credentials');
但同是 401,前端没法区分「没登录」和「账号密码错」。精细错误码应写在异常上,Filter 优先读它,而不是只按 HTTP status 做一张粗表。
export class BizException extends HttpException {
constructor(
readonly bizCode: number,
message: string,
httpStatus: HttpStatus
) {
super({ bizCode, message }, httpStatus);
}
}
// Service
throw new BizException(1004, 'Invalid credentials', HttpStatus.UNAUTHORIZED);
全局过滤器把所有异常收口成同一形状:
@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
catch(exception: unknown, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
let status = HttpStatus.INTERNAL_SERVER_ERROR;
let message = 'Internal server error';
let code = 1500;
if (exception instanceof BizException) {
status = exception.getStatus();
const body = exception.getResponse() as { bizCode: number; message: string };
code = body.bizCode;
message = body.message;
} else if (exception instanceof HttpException) {
status = exception.getStatus();
message = this.readHttpMessage(exception);
code = this.mapStatusToErrorCode(status); // 自带异常的兜底
} else {
// 未知错误:记日志,不要把内部 message 回给前端
console.error(exception);
message = 'Internal server error';
code = 1500;
}
response.status(status).json({
code,
msg: message,
data: null,
});
}
private readHttpMessage(exception: HttpException): string {
const body = exception.getResponse();
if (typeof body === 'string') return body;
if (body && typeof body === 'object' && 'message' in body) {
const raw = (body as { message: unknown }).message;
if (typeof raw === 'string') return raw;
if (Array.isArray(raw)) return raw.join('; ');
}
return exception.message;
}
private mapStatusToErrorCode(status: number): number {
switch (status) {
case HttpStatus.UNAUTHORIZED:
return 1001;
case HttpStatus.FORBIDDEN:
return 1003;
case HttpStatus.NOT_FOUND:
return 1100;
case HttpStatus.BAD_REQUEST:
return 1503;
default:
return 1500;
}
}
}
关键点:
@Catch()不传参数 = 抓住所有异常(不只是HttpException)- 有
bizCode用业务码;Guard / ValidationPipe 抛的自带异常,再用 HTTP status 粗映射 - 未知
Error对外统一「服务器错误」,内部message只打日志 - 永远返回
{ code, msg, data }
这样前端无论成功失败,解析路径都一样。
4. 请求链路对照
成功:
Controller return data
→ ResponseInterceptor map 成 { code:0, msg:'success', data }
→ 前端拿到统一成功包
失败:
Service throw BizException(1004, 'Invalid credentials', 401)
→ 不走成功拦截器的 map(异常打断 Observable)
→ HttpExceptionFilter catch
→ { code:1004, msg:'...', data:null }
→ 前端拿到统一错误包
可以记成:
正常 return 走 Interceptor;抛异常走 Filter。
两边约定同一信封字段,前端只认这一套。
5. HTTP 状态码 vs 业务错误码
两者分工不同:
| 维度 | HTTP status | 业务 code |
|---|---|---|
| 给谁看 | 网关、浏览器、通用客户端 | 业务前端、运营排障 |
| 粒度 | 粗(401/404/500) | 细(1001/1004/1100…) |
| 例子 | 401 Unauthorized | 1001 未登录 / 1004 凭证错误 |
常见分段(示例):
| 区间 | 含义 |
|---|---|
0 | 成功 |
1000–1099 | 认证鉴权 |
1100–1199 | 项目相关 |
1200–1299 | 文档相关 |
1500+ | 系统 / 校验类 |
mapStatusToErrorCode 只适合 Nest 自带的 UnauthorizedException / NotFoundException(Guard、ValidationPipe 也会抛这类)。
需要细分时,Service 抛 BizException,把 1004 写在异常上,Filter 原样放进信封。不要指望一张 HTTP status 对照表能表达全部产品语义。
6. 业务代码怎么写才干净?
Service:抛带业务码的异常
async login(email: string, password: string) {
const user = this.findUserByEmail(email);
if (!user) {
throw new BizException(1004, 'Invalid credentials', HttpStatus.UNAUTHORIZED);
}
// ...
}
不要在 Service 里手动拼:
return { code: 1004, msg: '...', data: null }; // 不推荐:和拦截器职责打架
Guard 挡下的未登录,仍是 Nest 的 UnauthorizedException,Filter 会粗映射成 1001。和「密码错」的 1004 就能分开。
Controller:继续薄
@Post('login')
login(@Body() body: { email: string; password: string }) {
return this.authService.login(body.email, body.password);
}
成功自动包;失败自动整形。
前端:按信封解包
http.interceptors.response.use((response) => {
const data = response.data;
if (data && typeof data === 'object' && 'code' in data) {
if (data.code === 0) {
return data.data; // 业务层只看到真正的 data
}
return Promise.reject(new Error(data.msg || '请求失败'));
}
return response;
});
7. 自定义异常信息时注意 getResponse() 形态
UnauthorizedException('Invalid credentials') 时,getResponse() 可能是字符串,也可能是:
{ "statusCode": 401, "message": "Invalid credentials", "error": "Unauthorized" }
所以 Filter 里要同时处理 string 和 object,否则 msg 可能变成 [object Object] 或拿不到可读文案。
校验类异常(如 ValidationPipe)的 message 还可能是字符串数组,进阶时可以再归一成一句或列表。
8. 和 Guard / JWT 的关系
Guard 鉴权失败时,底层同样会抛出 HTTP 异常(常见 401)。
只要全局 Filter 在,Guard 挡下的请求也会变成统一错误包,而不是「有的接口结构不一样」。
这正是系列串起来的好处:
- Module / Controller / Service 分层
- DI 接线
- Guard 守门
- Interceptor + Filter 统一出口
前端感知到的 API,始终是同一套语言。
9. 小结
- 统一信封:
{ code, msg, data },成功code === 0 - ResponseInterceptor:包装成功返回;SSE 按路径/装饰器跳过,不要赌
Content-Type已经写好 - ExceptionFilter:优先读异常上的业务码;未知错误不要把内部
message回给前端 - 业务层抛
BizException(code, msg, httpStatus),不要手写两套返回结构 - HTTP status 表达传输层语义,业务
code表达产品语义
对照前几篇,可以再多一句:
- 哪个 Controller 接请求?
- 哪个 Service 做业务?
- 哪个 Module 组装?
- 依赖从哪注入?
- 有没有 Guard?
- 成功谁包装、失败谁整形?前端拿到的信封长什么样?
下一篇会讲:Pipe 与 DTO 校验——为什么 @Body() 进来的脏数据,可以在进 Controller 之前就被拦下。
4752


:统一响应与异常处理&spm=1001.2101.3001.11974&articleId=163675673&d=1&t=3&u=13727e515a704fa88856e799fd5894f3)

被折叠的 条评论
为什么被折叠?



