【问题标题】:An error from an HTTP call is not caught when I subscribe to the result, but is caught in my HTTP interceptor订阅结果时未捕获来自 HTTP 调用的错误,但在我的 HTTP 拦截器中捕获了错误
【发布时间】:2020-08-13 23:17:49
【问题描述】:

我在 Angular 10 上(我之前在 8 上遇到过同样的问题)。在以下方法中,我在我的组件中订阅了一个 HTTP 请求:

    this.httpData.updateRadioAnswers(questions)
    .subscribe(
      result => this.requestResult = <any>result,
      error => {
        this.requestError = <any>error;
        console.log('error! '+this.requestError);
      },
      () => {
          console.log(this.requestResult);
      });

我也有这个 HTTP 拦截器:

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if (this.oauth.token && !req.headers.has('Authorization')) {
            req = req.clone(this.getHttpHeaders(null));
            return next.handle(req).pipe(
                tap((event: HttpEvent<any>) => { }, err => {
                    if (err instanceof HttpErrorResponse) {
                        console.log(err);
                    }
                })
            );
        } else {
            return next.handle(req);
        }
    }

当我的 HTTP 请求不成功时,我想处理我的组件(第一个块)中的错误,但“错误”中的代码永远不会被执行。但是,当发生错误时,拦截器中的“err”代码将被执行。当 HTTP 请求引发错误时,如何正确执行组件中的某些代码块?我不想在拦截器中处理这个问题,因为我想为不同的请求自定义错误消息,而不是拦截器中的它们都是一样的。

【问题讨论】:

    标签: angular angular-httpclient angular-http-interceptors


    【解决方案1】:

    试试这个:

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if (this.oauth.token && !req.headers.has('Authorization')) {
            req = req.clone(this.getHttpHeaders(null));
            return next.handle(req).pipe(
                catchError(error => throwError(error))
            )
        } else {
            return next.handle(req);
        }
    }
    

    【讨论】:

    • 我试过这个,但它仍然没有执行我在组件中订阅的错误部分的代码
    猜你喜欢
    • 2023-03-17
    • 1970-01-01
    • 2013-05-07
    • 2017-08-31
    • 1970-01-01
    • 2014-02-09
    • 1970-01-01
    • 2021-06-20
    • 2017-01-30
    相关资源
    最近更新 更多