网站建设销售好做,wordpress 宽版,网站排名优化需要多久,东平可信的网站建设需求
需要对接口的异常响应码#xff0c;手动设置message文本#xff01;#xff01;#xff01;
例如#xff1a;项目中使用multer中间件实现文件上传#xff0c;multer设置了文件大小限制#xff0c;该中间件校验文件时错误#xff08;文件超出#xff09;会自动响…需求
需要对接口的异常响应码手动设置message文本
例如项目中使用multer中间件实现文件上传multer设置了文件大小限制该中间件校验文件时错误文件超出会自动响应为
status: 413
statusMessage: Playload Too Large // 响应数据
{message: File too large,error: Payload Too Large,statusCode: 413
}但是我想自定义设置该message的文本甚至是设置statusMessage文本
实现
通过局部异常过滤器实现
custom-exception.filter.ts
import {ArgumentsHost,Catch,ExceptionFilter,HttpException,HttpStatus,
} from nestjs/common;// 码对应消息
export class CodeMessage {code: number;message: string;constructor(code: number, message: string) {this.code code;this.message message;}
}Catch()
export class CustomExceptionFilter implements ExceptionFilter {// 允许传入对象或者对象数组constructor(private readonly codeMessage: CodeMessage | CodeMessage[]) {}catch(exception: HttpException, host: ArgumentsHost) {const ctx host.switchToHttp(); // 获取请求上下文// const request ctx.getRequest(); // 获取请求上下文中的request对象const response ctx.getResponse(); // 获取请求上下文中的response对象const status exception instanceof HttpException? exception.getStatus(): HttpStatus.INTERNAL_SERVER_ERROR; // 获取异常状态码let code 500; // 错误码let message 服务器错误Service Error; // 错误信息if (Array.isArray(this.codeMessage)) {// 处理数组for (let i 0; i this.codeMessage.length; i) {const item this.codeMessage[i];if (item.code status) {code item.code;message item.message;}}} else if (Object.prototype.toString.call(this.codeMessage) [object Object] this.codeMessage.code status) {// 处理对象code this.codeMessage.code;message this.codeMessage.message;}// 设置返回的状态码 请求头发送错误信息response.setHeader(Content-Type, application/json; charsetgb2312);response.status(status);// response.statusMessage message; // 这里可以设置响应码说明文本, 但是不能设置中文// 响应数据response.send({message,code,// data: {},});}
}
使用 Post(test)UseFilters(new CustomExceptionFilter({ code: 413, message: 文件大小错误 }))test() {throw new HttpException(模拟异常, 413);return OK;}