Angular:拦截器在throwError之后如何检查类类型

我想检查来自拦截器的错误类类型执行throwError。(错误类类型表示一个类实现Error。)

但是,当我捕获到此错误时,尽管有其他错误类型,它仍然可以工作。 (在这种情况下,我想将错误检查为MyCustomError1,但尽管有MyCustomError2,它也可以工作。)

注意:MyCutomError1和MyCutomError2实现相同的Error类。

那么,我应该如何正确检查类型?

我的拦截器在这里。

@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.error);
                        default:
                            _error = errRes;
                            break;
                    }
                    return throwError(_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(()=>{})
zjfshy 回答:Angular:拦截器在throwError之后如何检查类类型

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3153368.html

大家都在问