2

I'm working on a NestJS backend that uses Firebase for authentication. I want to catch all and only the exception from Firebase (for example when users use an expired token) and translate them to actual HTTP errors. I want the HttpExceptions to be handled by the default filter.

I tried creating a new filter, but when I try to set the decorator like @Catch(FirebaseError) it doesn't compile saying 'FirebaseError' only refers to a type, but is being used as a value here. I also tried leaving the @Catch() without arguments and specifing the FirebaseError type on in the catch function, but it catches every exception.

// 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
  }
}

I want this filter to be called for FirebaseError exceptions, but if I write @Catch(FirebaseError) it doesn't compile, if I write @Catch() it catches every exception.

Kim Kern
  • 54,283
  • 17
  • 197
  • 195
Carlovan
  • 23
  • 6

1 Answers1

1

Have a look at the source code of ExceptionFilter:

ExceptionMetatype => exception instanceof ExceptionMetatype,

instanceof checks do not work on interfaces, only on classes. (It needs the prototype information on runtime.)


You could use an Interceptor to transform the errors to HttpExceptions instead. See this answer. (Of course, here you also cannot use instanceof with the interface.)

Kim Kern
  • 54,283
  • 17
  • 197
  • 195
  • 1
    That was the right way! I used an Interceptor and the `name` attribute of the `FirebaseError` interface instead of `instanceof` – Carlovan Mar 26 '19 at 16:07
  • Hey Carlovan and @Kim Kern, can you share that interceptor code, I'm stuck at it. –  Jul 02 '20 at 05:04
  • @DeepanshuDemla Have you had a look at the linked answer? https://stackoverflow.com/a/55238420/4694994 – Kim Kern Jul 02 '20 at 08:12