做app和做网站seo专员工资一般多少
需求
需要对接口的异常响应码,手动设置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; charset=gb2312');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';}