1. 先定义filters
http-exception.filter.ts
import {
ArgumentsHost,
Catch,
ExceptionFilter,
HttpException,
HttpStatus,
} from '@nestjs/common';
// ArgumentsHost 是Nestjs的核心类 用户在异常发生是,获取当前的上下文
// Catch 装饰器,用来告诉Nestjs 这个过滤器要捕获哪些异常
// ExceptionFilter 接口,定义过滤器必须实现 catch方法
// HttpException Nestjs内置的HTTP异常类
import { Response } from 'express';
// filters异常过滤器 作用是处理HttpException异常 并返回统一的响应格式
// filter的作用:
// 1. 统一错误响应格式
// 2.防止敏感信息泄露
// 3.错误日志记录
// 4. 异常转换
type HttpExceptionBody = {
statusCode?: number;
message?: string | string[];
error?: string;
};
// @Catch装饰器 捕获异常 Catch不传参 表示捕获所有的异常,传 HttpException 表示只捕获 HTTP 异常
@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
catch(exception: unknown, host: ArgumentsHost) {
// 检查是否是 HTTP 请求
if (host.getType() !== 'http') {
throw exception;
}
const request = host.switchToHttp().getRequest<Request>();
// 获取响应对象
// 切换到 HTTP 上下文并获取响应对象
const response = host.switchToHttp().getResponse<Response>();
// 获取异常状态码
// 如果异常是 HttpException 类型,返回异常的状态码
// 否则返回 HttpStatus.INTERNAL_SERVER_ERROR
// 这里使用 HttpStatus.INTERNAL_SERVER_ERROR 是因为默认的异常处理会返回 HttpStatus.INTERNAL_SERVER_ERROR
const status =
exception instanceof HttpException
? exception.getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR;
const exceptionResponse =
exception instanceof HttpException ? exception.getResponse() : undefined;
const body = this.normalizeExceptionBody(exceptionResponse);
response.status(status).json({
code: body.statusCode ?? status,
message: body.message ?? this.getDefaultMessage(status),
data: null,
path: (request as unknown as { path: string }).path,
timestamp: new Date().toISOString(),
});
}
private normalizeExceptionBody(
exceptionResponse: string | object | undefined,
): HttpExceptionBody {
if (typeof exceptionResponse === 'string') {
return { message: exceptionResponse };
}
if (exceptionResponse && typeof exceptionResponse === 'object') {
return exceptionResponse as HttpExceptionBody;
}
return {};
}
private getDefaultMessage(status: number): string {
return status === HttpStatus.INTERNAL_SERVER_ERROR
? 'Internal server error'
: 'error';
}
}
2. main.ts中引入,并且使用

转载自 CSDN-专业IT技术社区
原文链接:https://blog.csdn.net/qq_44603011/article/details/168537645



