如何@Catch()NestJS过滤器中的接口

问题描述 投票:2回答:1

我正在使用使用Firebase进行身份验证的NestJS后端。我想要捕获所有且仅来自Firebase的例外(例如,当用户使用过期的令牌时)并将其转换为实际的HTTP错误。我希望HttpExceptions由默认过滤器处理。

我尝试创建一个新的过滤器,但当我尝试设置装饰器像@Catch(FirebaseError)它不编译说'FirebaseError' only refers to a type, but is being used as a value here.我也尝试离开@Catch()没有参数和在FirebaseError函数指定catch类型,但它捕获每个异常。

// This code doesn't work
import { FirebaseError } from 'firebase';
import { ArgumentsHost, Catch, ExceptionFilter } from '@nestjs/common';

@Catch(FirebaseError)
export class FirebaseExceptionFilter implements ExceptionFilter<FirebaseError> {
  catch(exception: FirebaseError, host: ArgumentsHost) {
    // handle the exception
  }
}

我想要为FirebaseError异常调用这个过滤器,但如果我写@Catch(FirebaseError)它不编译,如果我写@Catch()它捕获每个异常。

javascript node.js typescript firebase nestjs
1个回答
0
投票

看看source codeExceptionFilter

ExceptionMetatype => exception instanceof ExceptionMetatype,

instanceof检查不适用于接口,仅适用于类。 (它需要关于运行时的原型信息。)


您可以使用Interceptor将错误转换为HttpExceptions。见this answer。 (当然,在这里你也不能在界面上使用instanceof。)

© www.soinside.com 2019 - 2024. All rights reserved.