Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Angular 2 http errors centrally

Tags:

angular

rxjs5

I have some code that handles all http access in a class that handles adding tokens. It returns an Observable. I want to catch errors in that class - in particular authentication problems. I am an RXjs beginner and can't figure out how to do this and still return an Observable. A pointer to some fairly comprehensive rxJS 5 documentation (that isn't source code!) would be useful.

like image 992
baldmark Avatar asked Jan 07 '23 16:01

baldmark


1 Answers

You can leverage the catch operator when executing an HTTP call within a service:

getCompanies() {
  return this.http.get('https://angular2.apispark.net/v1/companies/')
           .map(res => res.json())
           .catch(res => {
             // do something

             // To throw another error, use Observable.throw
             // return Observable.throw(res.json());
           });
}

Another approach could be to extend the HTTP object to intercept errors:

@Injectable()
export class CustomHttp extends Http {
  constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
    super(backend, defaultOptions);
  }

  request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
    console.log('request...');
    return super.request(url, options).catch(res => {
      // do something
    });        
  }

  get(url: string, options?: RequestOptionsArgs): Observable<Response> {
    console.log('get...');
    return super.get(url, options).catch(res => {
      // do something
    });
  }
}

and register it as described below:

bootstrap(AppComponent, [HTTP_PROVIDERS,
    new Provider(Http, {
      useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) => new CustomHttp(backend, defaultOptions),
      deps: [XHRBackend, RequestOptions]
  })
]);

What to use really depends on your use case...

like image 68
Thierry Templier Avatar answered Jan 16 '23 15:01

Thierry Templier