1

I'm new to angular2 and I do my http requests like this :

this.http.get(...).map(res=>res.json()).subscribe(data=>{
   //..do something
},err=>{

   if(err.status == 400){
      this.presentToast('Validation error');
   }else if(err.status == 403){
      this.presentToast('Authorization error'):
   }else if(err.status == 500){
      this.presentToast('Something wrong with server');
   }else ...
});

I wanted a custom message for each of the common status codes that users can understand, but the problem is I write these if and else blocks to each and every http request I do, and in every ts file I have, so basically I import ToastController in every ts file and write the presentToast function.

Is there anyway to make a generic error handler that is decorated in a way that it presents the custom rules/messages as a toast and make it DRY?

2
  • simply create some Global service and call each http request from there, by doing so you will be able to set global error handler messages as well as you can save no line of code Commented Feb 23, 2017 at 5:36
  • Ionic 2 has the Alerts check ionicframework.com/docs/v2/components/#alert Commented Feb 23, 2017 at 5:37

1 Answer 1

3

You can do it by creating a common Observable like this:

your common.ts will have this method: (Say, this component is CommonProvider as in written in CommonProvider class).

httpGetCall(url){
    return Observable.create(observer => {
        this.http.get(url)
        .map(res => res.json())
        .subscribe(data => {
            console.log("Your data : " , data);
            observer.next(data);
        },(err) => {
            console.log("Your error : ", err);
            observer.error(err);
            if(err.status == 400){
                this.presentToast('Validation error');
            }else if(err.status == 403){
                 this.presentToast('Authorization error'):
            }else if(err.status == 500){
                 this.presentToast('Something wrong with server');
            }else ...
        });
    });
}

From your calling method, you can do this:

@Component({
    templateUrl: "<your-html-path/code>",
    providers: [CommonProvider]
})
export class YourPage{
    constructor(private common: CommonProvider){
        this.common.httpGetCall(<url>)
        .subscribe(data => {
            //..do something
        },(err) => {
            //.. Any other operation or nothing to do as toast action is already done.
        })
    }
}

Though, this is just in case you need a common handler.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.