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

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

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

  1. import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
  2. import { Request, Response } from 'express';
  3. @Catch(HttpException)
  4. export class HttpExceptionFilter implements ExceptionFilter {
  5. catch(exception: HttpException, host: ArgumentsHost) {
  6. const ctx = host.switchToHttp();
  7. const response = ctx.getResponse<Response>();
  8. const request = ctx.getRequest<Request>();
  9. const status = exception.getStatus();
  10. response
  11. .status(status)
  12. .json({
  13. statusCode: status,
  14. timestamp: new Date().toISOString(),
  15. path: request.url,
  16. });
  17. }
  18. }
1zmg4dgp

1zmg4dgp1#

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

  1. app.use('/', filter);
  2. app.get('/',(req, res)=> {
  3. try {
  4. //do somethind
  5. throw new Error('My error')
  6. } catch(error) {
  7. return res.json({error: error})
  8. }
  9. });
  10. function filter(req, res, next) {
  11. const Res = res.json;
  12. res.json = function(data) {
  13. if(data.error && data.error instanceof Error) {
  14. data.error = data.error +': handled error';
  15. }
  16. Res.call(res, data);
  17. }
  18. next();
  19. }
展开查看全部

相关问题