nest 自定义异常过滤器

安装 nest

npm i -g @nestjs/cli

使用nest 创建异常过滤器

//可以查看nest cli 的帮助信息 
 nest -h  
// 使用 命令行工具 创建 异常过滤器模块  模块名称 error
nest g 	filter  error

以下是我自己写的 异常过滤可以参考一下
我们这边是服务器出错要返回抓取到的错误给前端
并返回statusCode = 10000
前端提示 抱歉出差弹框给用户
statusCode 不等于 500 或 200 的直接弹出message

import { ArgumentsHost, Catch, ExceptionFilter } from '@nestjs/common';
import { curry } from 'ramda';
@Catch()
export class ErrorFilter implements ExceptionFilter {
  catch(exception: any, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const res = ctx.getResponse();
    const req = ctx.getRequest();
    const send = this.wrapperSend(res);
    try {
      const status = exception.getStatus();
      let error = exception.getResponse();
      send(status, {
        statusCode: status,
        message: this.wrapperError(error),
        url: req.url,
        parms: this.wrapperParms(req),
      });
    } catch (error) {
      send(500, {
        statusCode: 10000,
        message: this.wrapperError(exception),
        url: req.url,
        parms: this.wrapperParms(req),
      });
    }
  }

  wrapperSend = curry((res, status, result) => {
    res.code(status).send(result);
    return res;
  });
  
  wrapperError(message) {
    if (typeof message === 'string') {
      return message;
    }
    return message.message;
  }
  wrapperParms(req) {
    let option = { POST: req.body, GET: req.query };
    return option[req.method];
  }
}

你可能感兴趣的:(typeorm,nest)