I find myself uncertain about the best practices for error handling in general. For instance, if I'm already handling errors in my service using catchError, is it necessary to also include an error handler in my subscription?
Here's an example of an http method in my service that utilizes catchError:
deleteTask(id: number): Observable<any>{
return this.http.delete(this.tasksUrl+'/'+`${id}`)
.pipe(
catchError(this.handleError)
);
}
private handleError(res: HttpErrorResponse | any) {
console.error(res.error || res.body.error);
return observableThrowError(res.error || 'Server error');
}
And in my component:
delete(id: number){
this.deleteService.deleteTask(id).subscribe(
(val) => {
/*post processing functionality not relevant to this question
*/
}
);
}
The angular documentation https://angular.io/guide/observables notes that the error handler in a subscription is optional:
myObservable.subscribe(
x => console.log('Observer got a next value: ' + x),
err => console.error('Observer got an error: ' + err),
() => console.log('Observer got a complete notification')
);
Therefore, in my case, would adding an error handler to my subscription provide additional benefits? For example:
delete(id: number){
this.deleteService.deleteTask(id).subscribe(
(val) => {
/*post processing functionality not relevant to this question
*/
},
err => console.error('Observer got an error: ' + err)
);
Could this catch errors that were missed by the catchError function in my service? It almost seems like a good practice to always include the error handler, so why is it considered optional? When should one opt for a subscription error handler over alternative error handling approaches?