Adding error handling on HttpClient

Hi Guys,

I’m asking for a help since I’m new to http client module of ionic. This problem is a little bit complex but let’s make it as short as possible. Basically, I was just wondering on how does HttpClient module handling error especially when the data being passed is a bad request for the server. What I wanted to do are to throw an exception ( alert controller ) and dismiss the loader whenever the Http transaction commit any error.

Here is the code for httpclient with loader:

  async post_register_clinician(data){
    const loading = await this.loading_controller.create({
      message: 'Loading',
      spinner : 'bubbles',
    });
    await loading.present();
 
    return new Promise(resolve=> {
      this.http_client.post(this.url+'register_as_clinician', JSON.stringify(data), http_options)
      .subscribe(res => {
        resolve(res);
        loading.dismiss();
        this.present_successful_registration_clinician();
      }), (err) => {
        reject(err);
        this.present_something_went_wrong();
        loading.dismiss();
      }
    });
  }

for alert window:

  async present_successful_registration_clinician() {
    const alert = await this.alert_controller.create({
      header: 'Registration Successful!',
      message: 'Congratulations! You are now successfully registered as clinician to App. You may now login your account.',
      buttons: ['Ok'],
    });
    await alert.present();
  }

  async present_something_went_wrong(){
    const alert = await this.alert_controller.create({
      header: 'Something Went Wrong!',
      buttons: ['Ok'],
    });
    await alert.present();
  }

I’m expecting that these lines of code handling the error but it doesn’t work:

(err) => {
        reject(err);
        this.present_something_went_wrong();
        loading.dismiss();
      }

Anyone could shed me a light to solve these following problem? :

  • Dismiss the loader if there is a failure
  • Display an alert window to notify the user

Thanks Guys! More power to Ionic :heart_eyes: