如何在 Nest in node 中实现异常过滤器?

how can I implement the exception filters in Nest in node?

我在 vanilla node 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,
      });
  }
}

您可以像下面这样编写过滤器 middleware/interceptor 来处理自定义错误,但是,您必须更新当前的实现以匹配解决方案

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();
}