0

拦截器代码:

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 代码,则错误又回来了。我希望拦截器进行通用处理,但也允许调用函数在需要时处理错误。可能吗?

4

1 回答 1

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();
        }
      }
    );

检查我的答案中的评论

于 2017-11-30T22:16:33.410 回答