4

I'm trying to consume a rest api, with a simple http get. When there's no registers my api response a error 500 like that:

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

So, i’m wondering how i can write an interceptor to handle all kind of http error to prevent logging the error @ browser’s console.

My 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 {
}

My 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.`);
            }          
        });

    }
}

My 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 is where a make my get call

 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 Answers3

1

Actually is not possible to achieve what you want, is just default browser behavior, see jeff's response @ angular's github:

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

0

I dont really understand you goal, but if you need to handle the error caused by an ajax call you need to react to the observable .onError function

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

However, onError callbacks are treated as a terminal event, in case you want to continue the stream, you should use a .catch operator

If you are speaking about angularjs interceptor, i'm afraid there is no current solution as i know. But you can easily achieve such functionality inside your services. Most of the times error resolution is varied, so unless youre building an audit service or a loading bar appwide the best approach is to apply a more specific logic

LookForAngular
  • 1,030
  • 8
  • 18
0

You could use GlobalErrorHandler that extends the ErrorHandler and implement the handleError() method. It shouldnt throw it to the browser then.

lohiarahul
  • 1,432
  • 3
  • 22
  • 35