【问题标题】:how can I implement the exception filters in Nest in node?如何在节点中的 Nest 中实现异常过滤器?
【发布时间】:2021-07-25 22:43:18
【问题描述】:

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

【问题讨论】:

  • 香草还是 express.js?我很少看到有人比后者更低。
  • 您是否要为一个项目使用两个框架? nest.js 和快递?如果是,那真是个坏主意。

标签: node.js nestjs


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2021-05-04
    • 2022-08-05
    • 1970-01-01
    • 2011-01-03
    • 1970-01-01
    • 2019-01-11
    • 1970-01-01
    • 2014-08-03
    • 2023-02-06
    相关资源
    最近更新 更多