Catch Blocks in Services & Subscription Error Callbacks in Components
This is what I have come to use as my project has developed. The catch block in the service is responsible for transforming the error. The error callback in the component is responsible for updating any view logic.
Service
I rarely get back the data I need in the format I need from the api, so I transform the data within a .map() method. Then I attach a catch block to the sequence.
// Service Class
getTableData(): Observable<Table>{
return this.http.get('url')
.map(res => {
// transform data as needed
return transformedData;
}
.catch(err => {
// transform error as needed
let transformedError = GlobalFunction.transformError(err);
return Observable.throw(transformedError);
}
}
now I perform whatever transform I want when an error occurs. For example, I may call a global method that converts an error into a user friendly response
// GlobalFunction Class
transformError(err){
switch(err.status){
case 404:
return {
status: err.status,
message: 'Oops, it looks like that resource was not found'
}
break;
}
}
Component
Now in my component, I subscribe to the sequence
// Component Class
ngOnInit(){
this.loading = true;
this.error = false;
this.subscription = this.service.getTableData().subscribe(
res => {
this.table = res;
this.loading = false;
},
err => {
this.message = err.message;
this.error = true;
this.loading = false;
}
);
}
By containing all of my data transform in the service, I have kept the view logic nice & lean. I believe this approach keeps the pieces separate. The service provides the data & the component updates the view.