NESTJS Get the execution context within the exception filter

Viewed 460

I store user identification data in the execution context with my authentication guard. I would like to retrieve this context in the exception filter so I can set sentry metadata from user identification data. Exception filter however receives ArgumentsHost from the constructor, not the execution context where user identification data are stored. Can I somehow retrieve the execution context within the exception filter?

2 Answers

Have you tried it like it is specified in the docs?

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp()
    let request = ctx.getRequest<Request>()
    
    /* ... */
  }
}

So I found that identification data are in the execution context only for a short time being and vanish when accessed with paramDecorator. So I store my identification data (ReqUser) in a request object specific to each context type. Now I access those contexts with help of the Helper class from guards, interceptors, and exception filters.

export class Helpers {
  public static getReqUserDestinationFromHost(host: ArgumentsHost): Record<string, unknown> {
    switch (host.getType<ContextType | 'graphql'>()) {
      case RequestType.HTTP:
        return host.switchToHttp().getRequest();
      case RequestType.GRAPHQL:
        return GqlArgumentsHost.create(host).getArgByIndex(2);
      case RequestType.WEB_SOCKET:
        throw new NotImplementedException('WEB_SOCKET ReqUser destination is not reachable');
      case RequestType.RPC:
        throw new NotImplementedException('RPC ReqUser destination is not reachable');
    }
    throw new NotImplementedException('Unable to identify ReqUser destination');
  }

  public static getReqUserDestinationFromContext(
    context: ExecutionContext
  ): Record<string, unknown> {
    switch (context.getType<ContextType | 'graphql'>()) {
      case RequestType.HTTP:
        return context.switchToHttp().getRequest();
      case RequestType.GRAPHQL:
        return context.getArgByIndex(2);
      case RequestType.WEB_SOCKET:
        throw new NotImplementedException('WEB_SOCKET ReqUser destination is not reachable');
      case RequestType.RPC:
        throw new NotImplementedException('RPC ReqUser destination is not reachable');
    }
    throw new NotImplementedException('Unable to identify ReqUser destination');
  }
}
Related