Angular 4.3中的HttpInterceptor:拦截400个错误响应 [英] HttpInterceptor in Angular 4.3: Intercepting 400 error responses

查看:137
本文介绍了Angular 4.3中的HttpInterceptor:拦截400个错误响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想拦截401和其他错误,以便做出相应的反应.这是我的拦截器:

I would like to intercept 401 and other errors in order to react accordingly. This is my interceptor:

import { LoggingService } from './../logging/logging.service';
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent, HttpResponse, HttpErrorResponse } from '@angular/common/http';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';

@Injectable()
export class TwsHttpInterceptor implements HttpInterceptor {

    constructor(private logger: LoggingService) { }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        this.logger.logDebug(request);    
        return next.handle(request)
            .do(event => {
                if (event instanceof HttpResponse) {
                    this.logger.logDebug(event);
                }
            });
    }
}

虽然此方法适用于200个请求,但它不会拦截错误响应

While this works well for 200 requests, it does not intercept the error respsonses

我在chrome开发控制台中看到的全部是这样:

All I see in chrome's dev console is this:

zone.js:2616 GET http://localhost:8080/backend/rest/wrongurl 404(不是 找到)

zone.js:2616 GET http://localhost:8080/backend/rest/wrongurl 404 (Not Found)

或者这个

zone.js:2616 GET http://localhost:8080/backend/rest/url 401 (未经授权)

zone.js:2616 GET http://localhost:8080/backend/rest/url 401 (Unauthorized)

我希望我的拦截器可以处理这个问题.我想念什么?

I would like my interceptor to deal with this. What am I missing ?

推荐答案

Http沿着可观察对象的错误流发送错误,因此您需要使用.catch来捕获它们(您可以阅读有关此此处).

Http sends errors down the error stream of an observable so you will need to catch them with .catch (you can read more about this here).

return next.handle(request)
  .do(event => {
    if (event instanceof HttpResponse) {
      this.logger.logDebug(event);
    }
  })
  .catch(err => { 
    console.log('Caught error', err);
    return Observable.throw(err);
  });

这篇关于Angular 4.3中的HttpInterceptor:拦截400个错误响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆