Restangular: Failed requests stops execution with await

Issue

I have an error interceptor like below:

RestangularProvider.addErrorInterceptor((response) => {

    const error = EnumerableFromObject(response.error.Errors)
      .Select(i => i.Value.Message)
      .FirstOrDefault();
    toastr.error(error, "Error");

    return true;
  });
}

Below is the code of my auth service:

  async Login(login: string, password: string) {
    const sessions = this.rest.all("sessions");
    const params = {Login: login,Password: password };
    const response = await sessions.post(params).toPromise();
    return response;
  }

And this is how I am calling it in my component:

this.loader.show();
const response = await this.authorizationService.Login(login, password);
this.loader.hide();

So I have to hide loader after the service is completed, failed or not.

My issue is when a request fails with any reason – like wrong credentials – execution stops, & it never reaches to this.loader.hide();

How can I handle this without using then. In my project all methods are called with await. So I can’t remove await & use then. It will require so much rework.

Can anyone tell me what I am missing here?

Solution

The problem is you do not have any error handling in place. If your request fails the await part will throw an exception – that means the function is exited –> your .hide() call is never reached

To handle this you can wrap it inside a try catch, e.g.

this.loader.show();
try {
    const response = await this.authorizationService.Login(login, password);
} catch (error) {
    // do something with the error here
}
this.loader.hide();

Answered By – Nicolas Gehlert

Answer Checked By – Mary Flores (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.