处理http错误的HttpInterceptors角度为4.3

时间:2017-07-19 21:01:14

标签: angular angular-http-interceptors

我正在尝试使用简单的http get来使用rest api。当没有寄存器时,我的api响应错误500就像那样:

{ "errors": [ { "code": "500", "message": "no registers." } ]}

所以,我想知道如何编写一个拦截器来处理所有类型的http错误,以防止记录错误@浏览器的控制台。

我的app.module.ts

import { NgModule, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { sharedConfig } from './app.module.shared';
import 'rxjs/add/operator/toPromise';
import { NoopInterceptor } from "./app.interceptor";

@NgModule({
    bootstrap: sharedConfig.bootstrap,
    declarations: sharedConfig.declarations,
    imports: [
        BrowserModule,
        FormsModule,
        HttpClientModule,
        ...sharedConfig.imports
    ],
    providers: [
        { provide: 'ORIGIN_URL', useValue: location.origin },
        {
            provide: HTTP_INTERCEPTORS,
            useClass: NoopInterceptor,
            multi: true,
        }
    ]
})
export class AppModule {
}

我的app.interceptor.ts

import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse } from '@angular/common/http';
import { Observable } from "rxjs/Observable";
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';
import { HttpErrorResponse } from "@angular/common/http";

@Injectable()
export class NoopInterceptor implements HttpInterceptor {

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const started = Date.now();

        return next.handle(req)
        .do(event => {
            debugger;
            if (event instanceof HttpResponse) {
                const elapsed = Date.now() - started;
                console.log(`Request for ${req.urlWithParams} took ${elapsed} ms.`);
            }          
        });

    }
}

我的app.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Config } from "./app.constantes";

@Injectable()
export class AppService {
    protected config: Config;
    constructor(private http: HttpClient) {
        this.config = new Config();            
    }   

    get(service: string, complementos?: any, parametros?: any) {
        var complemento = complementos != null && complementos.length > 0 ? complementos.join('/') : '';
        var url = this.config.SERVER + service + this.config.TOKEN + '/' + complemento;
         return this.http.get(this.config.SERVER + service + this.config.TOKEN + '/' + complemento);
    }

}

compra.component.ts是让我接到电话的地方

 consultaPeriodoCompra(mes: any): void {
        var lista = null;

        this.service.get(this.config.CONSULTA_ULTIMAS_COMPRAS, ['2', mes.anoMes])
            .subscribe((response) => {               

                this.atualizaLista(mes, response['payload'].listaTransacao);
            },
            (err) => {                    
                this.atualizaLista(mes, []);
            });

    }

that it's what i want to prevent

3 个答案:

答案 0 :(得分:1)

实际上不可能实现你想要的,只是默认的浏览器行为,请参阅jeff的回复@ angular&#39; s github:

https://github.com/angular/angular/issues/8832

答案 1 :(得分:0)

我真的不了解你的目标,但如果你需要处理由ajax调用引起的错误,你需要对可观察的.onError函数作出反应

this.httpService.get(url)
.subscribe(
    // onnext
    () => [...],
    // onError
   (err) => [...]
);

但是,onError回调被视为终端事件,如果你想继续流,你应该使用.catch运算符

如果你在谈论angularjs拦截器,我恐怕目前没有解决方案。但您可以轻松地在服务中实现此类功能。 大多数情况下,错误解决方案是多种多样的,因此,除非您构建审计服务或appwide的加载栏,否则最佳方法是应用更​​具体的逻辑

答案 2 :(得分:0)

您可以使用扩展ErrorHandler的GlobalErrorHandler并实现handleError()方法。它不应该把它扔到浏览器上。