I am using the angular6 HTTPClient in my service and would like to maintain the next and err paths of the Observable to the subscriber.
e.g. My component looks something like this:
private myFun(query: string) {
this.myService.login(data).subscribe(next => {
// Do successful stuff
console.log('Got the data: ' + next);
},
err => {
// Handle all errors here
console.error('good luck next time')
});
}
My service is using a pipe along with the map and catchError.
private findData(in: string): Observable<string> {
return this.http.post<string>(self.url, '')
.pipe(
map( response => {
//Check the data is valid
if (this.dataValid(response)){
return this.convertedData(response);
} else {
throw new Error('failed parsing data');
}
}),
catchError(this.handleError)
);
}
I can detect the parsing issue and raise the error via catchError but what I am struggling to understand is how to process the catchError.
The error handler looks like this:
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// Client Side Error
console.error('Client side error:', error.error.message);
} else if (error.message === 'failed parsing data') {
// Client Side Processing Error
console.error(error.message);
return throwError(error.message);
} else {
// Service Side Error
console.error(`Server returned code ${error.status}, ` + `body was: ${error.error}`);
}
// return an observable error message
return throwError('failed to contact server');
}
It does the job but I can't help thinking there must be a better, more Angular/RxJS way, of doing this.
What I would have expected is to have hit the 'error.error instanceof ErrorEvent' path of the error handler. I don't understand how the "error: HttpErrorResponse" parameter is being updated - I am just throwing a "new Error('failed parsing data');".
Any advice/suggestions?