3

I want to check the error class type which comes from intercepter executes throwError.(The error class type means a class implements Error.)

But, when I caught this error, it works inspite of another error type. (In this case, I want to check error as MyCustomError1, but, it works despite MyCustomError2.)

Note: MyCutomError1 and MyCutomError2 implements same Error class.

So, How should I check the type appropriately ?

My intercepter is here.

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const _req = req.clone();
        return next.handle(_req)
            .pipe(
                catchError((errRes: HttpErrorResponse) => {
                    let _error: Error = null;
                    switch (errRes.status) {
                        case 401:
                            _error = new MyCustomError1(errRes.name, errRes.message, errRes.error);
                            break;
                        case 503:
                            _error = new MyCustomError2(errRes.name, errRes.message, errRes.error);
                        default:
                            _error = errRes;
                            break;
                    }
                    return throwError(_error);
                })
            );
    }
}

Then, I want to catch the error such as below.

Note: I will use this service in my component and handle the error.

this.myService.doSomething()
  .pipe(
        catchError((err: Error) => {

        // How should I check the type?
        // In the case of MyCustomError2, this returns true.
        if(err instanceof MyCustomError1){
          // error handling
        }
        return EMPTY;
      })
   ).subscribe(()=>{})
  • 1
    this might help https://stackoverflow.com/questions/17484002/why-javascript-typeof-returns-always-object and this https://stackoverflow.com/questions/332422/get-the-name-of-an-objects-type – Madhawa Priyashantha Nov 06 '19 at 10:03
  • Thank you, I didn't understand it. That helps a lot. But, what I want to know truly is to distinguish an error class type from another error type class. I modified my post. If you are available, please check it again. – Too crying man Nov 06 '19 at 10:21
  • 1
    Sorry, I missed the second link. When I tried to compare objects by constructor, it seems to work. I will study typescript. Maybe my problem is resolved. Thank you. – Too crying man Nov 06 '19 at 10:37
  • By the way, it was not Typescript but Javascript specifications. Thank you! – Too crying man Nov 06 '19 at 10:52
  • yes this is js.hope you have fixed the issue – Madhawa Priyashantha Nov 06 '19 at 11:20

0 Answers0