Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error handling with Observables in Angular 2

Tags:

angular

I'm trying to pass any errors that might occur in an HTTP request to a common logging service from all my services:

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';

constructor(logger: LoggerService) { }

doSomething(): Observable<any> {
    return this.http
        .post('/foo/bar', {})
        .catch(this.notifyErrors);
}

protected notifyErrors(error: any): Observable<any> {
    this.logger.log(error);

    return Observable.throw(error);
}

Unfortunately, inside the notifyErrors method, this is lost. I've tried defining this as a fat arrow, but i get type errors from the TS compiler. I've used the exact syntax in the Observable documentation.

like image 694
vinnylinux Avatar asked Mar 29 '17 16:03

vinnylinux


People also ask

How does Angular handle error in Observable?

Catch errors in the observable stream Another option to catch errors is to use the CatchError Operator. The CatchError Operators catches the error in the observable stream as and when the error happens. This allows us to retry the failed observable or use a replacement observable.

How will you handle errors in angular 2 applications?

Angular 2 applications have the option of error handling. This is done by including the ReactJS catch library and then using the catch function. Let's see the code required for error handling. This code can be added on top of the chapter for CRUD operations using http.

Does Observable complete after error?

In an Observable Execution, zero to infinite Next notifications may be delivered. If either an Error or Complete notification is delivered, then nothing else can be delivered afterwards.

How do you return an Observable error?

In order to retry the failed observable immediately after the error occurs, all we have to do is return the Errors Observable without any further changes. res => console. log('HTTP response', res), err => console.


1 Answers

If you pass function references, you need to fix this

 .catch(this.notifyErrors.bind(this));

or alternatively

 .catch(() => this.notifyErrors());

See also https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

like image 62
Günter Zöchbauer Avatar answered Oct 08 '22 01:10

Günter Zöchbauer