我正在使用使用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()
它捕获每个异常。
看看source code的ExceptionFilter
:
ExceptionMetatype => exception instanceof ExceptionMetatype,
instanceof
检查不适用于接口,仅适用于类。 (它需要关于运行时的原型信息。)
您可以使用Interceptor
将错误转换为HttpExceptions
。见this answer。 (当然,在这里你也不能在界面上使用instanceof
。)