Angular 5日志拦截器抛出错误但调用函数无法读回错误

时间:2017-11-30 21:41:11

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

拦截器代码:

import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
// import { tap, map, catchError } from 'rxjs/operators';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';

@Injectable()
export class LogInterceptor implements HttpInterceptor {

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        console.log(`HTTP: ${req.urlWithParams}`);

        return next.handle(req)
            .catch((err, caught) => {
                console.log(err);
                if (err.error instanceof Error) {
                    // A client-side or network error occurred. Handle it accordingly.
                    console.log('An error occurred:', err.error.message);
                } else {
                    // The backend returned an unsuccessful response code.
                    // The response body may contain clues as to what went wrong,
                    console.log(`Backend returned code ${err.status}, body was: ${err.error.message}`);
                }
                return Observable.throw(err);
            })
            .do(event => {
                console.log(event);
                if (event instanceof HttpResponse) {
                    console.log(event.body);
                }
            });
    }

}

拦截器正在工作,但调用函数无法读取错误,并且它总是为空。

调用函数

this.http.post<Asset>(`whatever.php`, {}).subscribe(
  _data => console.log(data), 
  _err => console.log(_err) // <- this _err is always NULL 
);

如果在拦截器中删除了catch代码,则会返回错误。我希望拦截器执行泛型处理,但也允许调用函数在需要时处理错误。有可能吗?

1 个答案:

答案 0 :(得分:0)

return next.handle(req).do(
      (event: HttpEvent < any > ) => {
        if (event instanceof HttpResponse) {
          console.log('--> event: ', event);
          console.log('--> status: ', event.status);
          this._spinnerService.requestEnded();
        }
      },
      (err: any) => { <-- The error is caught here. You didn't define any Error callback, hence it's null during your subscription.
        if (err instanceof HttpErrorResponse) {
          console.log('--> error: ', err);
          console.log('--> errorStatus: ', err.status);
          this._spinnerService.requestEnded();
        }
      }
    );

检查我的答案中的评论