【问题标题】:HttpInterceptors handling http errors angular 4.3HttpInterceptors 处理 http 错误 Angular 4.3
【发布时间】:2017-09-05 09:08:41
【问题描述】:

我正在尝试使用一个简单的 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

【问题讨论】:

  • 你的 api 是否也返回状态码 500?或者它返回一个带有上述错误的 200?
  • 它也返回状态码 500。
  • 阻止浏览器登录是什么意思?这是你唯一的目的吗?
  • @LookForAngular 我放了一些代码示例以便更容易理解。
  • 角度无法阻止失败的 ajax 调用日志记录。这更像是一个镀铬问题而不是一个角度问题。 stackoverflow.com/questions/4500741/…

标签: angular angular-http-interceptors


【解决方案1】:

其实不可能实现你想要的,只是浏览器默认行为,见jeff的回复@angular的github:

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

【讨论】:

    【解决方案2】:

    我不太了解你的目标,但是如果你需要处理由 ajax 调用引起的错误,你需要对 observable .onError 函数做出反应

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

    然而,onError 回调被视为一个终端事件,如果你想继续流,你应该使用 .catch 操作符

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

    【讨论】:

    • 我放了一些代码示例以便更容易理解。
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2012-11-16
      • 2016-07-12
      • 2017-12-16
      • 1970-01-01
      • 2018-11-30
      • 1970-01-01
      • 1970-01-01
      • 2017-12-09
      • 1970-01-01
      相关资源
      最近更新 更多