当前位置: 首页 > news >正文

nest定义响应码message文本

需求

需要对接口的异常响应码,手动设置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';}
http://www.lryc.cn/news/426797.html

相关文章:

  • Java | Leetcode Java题解之第342题4的幂
  • 【日常开发】java中一个list对象集合 将字段a为 大豆 小麦 玉米等元素放在最前面 并组成新集合
  • C++ 设计模式——原型模式
  • 【Harmony OS 4.0】待办列表案例
  • 快速把文件名统计到excel表的方法
  • 开源通用验证码识别OCR —— DdddOcr 源码赏析(一)
  • 上升ECMAScript性能优化技巧与陷阱(下)
  • 用7EPhone云手机进行TikTok的矩阵运营
  • 谷歌浏览器下载文件被阻止怎么解除
  • apt E: 无法定位软件包 winehq-stable
  • P2460[SDOI2007] 科比的比赛
  • linux学习--第二天
  • 使用 Flask、Celery 和 Python 实现每月定时任务
  • 【c语言】整数在内存中的储存(大小端字节序)
  • 浅谈SIMD、向量化处理及其在StarRocks中的应用
  • 【ML】Image Augmentation)的作用、使用方法及其分类
  • 设计模式六大原则(一)--单一职责原则
  • c语言学习,malloc()函数分析
  • 【运维项目经历|041】上云项目-物理机迁移到阿里云
  • 分组并合并其它列的非空值 --Excel难题#83
  • VM相关配置及docker
  • Redis中Set数据类型常用命令
  • mysql误删数据恢复记录
  • 论文阅读:Real-time Controllable Denoising for Image and Video
  • 【Kubernetes】虚拟 IP 与 Service 的代理模式
  • 深度学习·Pytorch
  • fastzdp_sqlmodel新增get_first和is_exitsts方法
  • 嵌入式软件--数电基础 DAY 3
  • 【生成式人工智能-十五-经典的影像生成方法-GAN】
  • python 已知x+y=8 求x*y*(x-y)的最大值