baldmark February 2016

Handling Angular 2 http errors centrally

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.

Answers


Thierry Templier February 2016

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...

Post Status

Asked in February 2016
Viewed 1,416 times
Voted 6
Answered 1 times

Search




Leave an answer