【问题标题】:NestJS Interceptor with async method in controllerNestJS拦截器在控制器中具有异步方法
【发布时间】:2021-09-04 10:07:18
【问题描述】:

我需要通过拦截器拦截控制器中方法的结果(以及错误,如果有的话)。 该方法是异步的。

当我抛出错误时,我的拦截器会意识到并且可以执行一些逻辑。但是当一切正常时,我无法让我的拦截器知道它没问题,并且也做一些逻辑。

这是我的控制器方法:

@UseInterceptors(GatewayInterceptor)
@Get([ ':id?', ':id/relationships/:type', 'relationships/:type' ])
public async handleGet(
    @Req()              req             : Request,
    @Res()              res             : Response,
) {
    await this.gatewayService.redirect_to_database_service_GET()
    .then( data => res.send(data))
    .catch(err => {  throw( new HttpException( err.message, HttpStatus.BAD_REQUEST) ) })
}

还有拦截器:

export class GatewayInterceptor implements NestInterceptor {

public  intercept(context: ExecutionContext, next: CallHandler) {

  const request = context.switchToHttp().getRequest();

   return next
     .handle()
     .pipe(
      tap( () => { 
       console.log('VALUE')
       this.decrement_user_acces_on_service(request)
      }),
      catchError(error => {
       console.log('ERROR')
       throw error
      })
     );
   }
}

console.log('ERROR') 因错误而被触发,但当一切正常时我无法获取 console.log('VALUE')。

有人知道我的错误在哪里吗?

感谢任何可以帮助我的人!

【问题讨论】:

    标签: javascript typescript asynchronous nestjs interceptor


    【解决方案1】:

    好吧,我的错,我的控制器出错了:

    等待这个。网关服务。重定向到数据库服务获取()。然后 (data => res.send (data))

    没有解析任何数据,所以它不起作用。

    没关系,我的拦截器可以知道什么时候有错误或者什么时候可以处理数据。

    无论如何,它可能对某人有用。

    【讨论】:

      猜你喜欢
      • 2018-03-31
      • 2021-02-11
      • 1970-01-01
      • 2021-05-11
      • 1970-01-01
      • 1970-01-01
      • 2018-11-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多