如何在节点的嵌套中实现异常过滤器?

quhf5bfb  于 2021-10-10  发布在  Java
关注(0)|答案(1)|浏览(250)

我需要像这样的东西在香草节点js,有人可以引导我通过吗?

import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import { Request, Response } from 'express';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    const status = exception.getStatus();

    response
      .status(status)
      .json({
        statusCode: status,
        timestamp: new Date().toISOString(),
        path: request.url,
      });
  }
}
1zmg4dgp

1zmg4dgp1#

您可以编写如下所示的过滤器中间件/拦截器来处理自定义错误,但是,您必须更新当前实现以匹配解决方案

app.use('/', filter);

app.get('/',(req, res)=> {
    try {
        //do somethind
        throw new Error('My error')
    } catch(error) {
        return res.json({error: error})
    }
});

function filter(req, res, next) {
    const Res = res.json;
    res.json = function(data) {
        if(data.error && data.error instanceof Error) {
            data.error = data.error +': handled error';
        }
        Res.call(res, data);
    }
    next();
}

相关问题