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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With