axios NestJS中的全局拦截器、响应Map和库特定响应

2hh7jdfx  于 2023-11-18  发布在  iOS
关注(0)|答案(1)|浏览(140)

我试图在NestJS中使用“特定于库”的响应对象和全局拦截器,但它不起作用,正如我从文档中了解的那样,这是预期的:
响应Map:
响应Map特性不适用于特定于库的响应策略(禁止直接使用@Res()对象)。
我使用库特定响应的原因是因为我需要动态模板渲染:
如果应用程序逻辑必须动态地决定呈现哪个模板,那么我们应该使用@Res()装饰器,并在路由处理程序中提供视图名称,而不是在@Render()装饰器中提供
我需要动态模板的原因是因为最终的模板是基于用户语言(es/homefr/homeen/home等)决定的。是的,这些模板根据语言有不同的内容(不仅仅是翻译的文字)。
最终的目标是通过一个全局拦截器来处理400,500错误。网站从一个API(通过axios)获取数据,所以当下游有错误时,让它冒泡并在一个单独的地方被捕获会非常方便,这个地方可以很好地呈现404,500等。
有什么办法能最好地避开这个限制吗?
谢谢

kiz8lqtg

kiz8lqtg1#

最后,按照Jay McDoniel的建议,我使用了一个“捕捉一切”异常过滤器,成功地得到了我想要的结果。
不得不把那页上的几件事合并结合起来:

import { Catch, ArgumentsHost, HttpException, HttpStatus } from '@nestjs/common';
import { BaseExceptionFilter } from '@nestjs/core';
import { Response, Request } from 'express'; // note the casting to Express types

@Catch()
export class AllExceptionsFilter extends BaseExceptionFilter {
    catch(exception: unknown, host: ArgumentsHost) {

        const ctx = host.switchToHttp();
        const response = ctx.getResponse<Response>();
        const request = ctx.getRequest<Request>();
        const httpStatus =
            exception instanceof HttpException
                ? exception.getStatus()
                : HttpStatus.INTERNAL_SERVER_ERROR;

        response.status(httpStatus);
        response.render(`views/errors/${httpStatus}`);
    }
}

字符串
并在引导过程中添加以下内容:

const app = await NestFactory.create<NestExpressApplication>(AppModule);
  const { httpAdapter } = app.get(HttpAdapterHost);
  app.useGlobalFilters(new AllExceptionsFilter(httpAdapter));
  ...

相关问题