Restangular: The use of await causes execution to halt when requests fail

I encountered an error interceptor that looks like this:

RestangularProvider.addErrorInterceptor((response) => {

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

    return true;
  });
}

Here is a snippet of my auth service code:

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 the way I am invoking it in my component:

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

My current challenge is when a request fails due to any reason, such as incorrect credentials, the execution stops before reaching this.loader.hide();

How can I address this issue without using then? All methods in my project are invoked with await, so switching to then would involve significant rework.

If anyone has suggestions on what might be missing or how to resolve this, please share.

Answer №1

The issue lies in the absence of error handling. If there is a failure in your request, the await section will trigger an exception, leading to the function exiting before reaching the .hide() call.

To rectify this, you can enclose it within a try-catch block like so:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using TypeScript, pass an image as a prop in a Styled Component

I am facing an issue with the code below that is supposed to display the "NoBillsLaptopPNG.src" image on the screen, but for some reason, the image is not showing up. The images are being imported correctly, so I'm unsure why the image is not appeari ...

Need for utilizing a decorator when implementing an interface

I am interested in implementing a rule that mandates certain members of a typescript interface to have decorators in their implementation. Below is an example of the interface I have: export interface InjectComponentDef<TComponent> { // TODO: How ...

What is the best way to incorporate a JavaScript function into an Angular 2 template?

I need a slider for my project and I am using AdminLTE <input type="text" value="" class="slider form-control" data-slider-min="-200" data-slider-max="200" data-slider-step="5" data-slider-orientation="horizontal" data-slider-sele ...

New substitute for extending the extent in OpenLayers 4

I am currently in the process of migrating my code from OpenLayers 3 to OpenLayers 4 using TypeScript. Previously, I had a code snippet that extended the extent of my map so that all vector shapes I drew would be visible upon loading... angular.forEach(w ...

Creating Test Cases for Service Response Validation

I am currently attempting to unit test an API within my ngOnInit method. The method is responsible for making a call to the service in order to fetch details. If the details are not undefined, an array called 'shoeDataResponse' of type *shoeData ...

Guide to obtaining ngPrime autocomplete text when the button is clicked within Angular 6

I am currently utilizing the ngPrime autocomplete feature to retrieve data from a service. My goal is to capture the text entered in the autocomplete field whenever a button is clicked. I attempted to access the value using getElementById.value within th ...

Extending parent context in dependencies through OOP/Typescript as an alternative to using "extends"

Introducing a custom class called EventBus has been a game-changer for me. This class allows for easy attachment of on/off/once methods to any class that extends it, enabling the creation of an array of events that can be listened to. Currently, I find my ...

Tips for maintaining consistent column width when scrolling down (column juggling) within a table in your Angular application

Take a look at this preview of the app I'm currently developing. https://stackblitz.com/edit/angular-ivy-3mrzkr In order to handle the large amount of data in my real app, I needed to incorporate a third-party scrolling module. After testing out cdk ...

Issue with Angular polyfill in IE11: The core-js version 3.6.5 method es.string.split.js is having trouble parsing the regex /^|s+/ when used with

Angular 10, d3 5.16.0, and core-js 3.6.5 In the midst of it all, d3-drag triggers d3-dispatch, which in turn invokes a function called .parseTypenames. function parseTypenames(typenames, types) { return typenames.trim().split(/^|\s+/).map(functio ...

Unable to compile angular project - Encountering Error - The data path ".builders['app-shell']" must contain the mandatory property 'class'

While attempting to construct an angular project, I encountered the following error: Data path ".builders['app-shell']" should have the required property 'class'. Error: Schema validation has failed with the errors noted below: Data pa ...

Is it possible to observe and retrieve sub-documents in Firestore instead of the entire document? Specifically for time series data

My database setup involves a Firebase Firestore where each document represents hourly time buckets for storing IoT sensor data. Each document includes: The latest humidity reading The latest temperature reading An array containing all humidity and temper ...

Refreshing the parent component when the modal component is closed

I have a component that displays rows from a database in a table. This component includes an "Add" button. When the "Add" button is clicked, a modal pops up with a form to insert a new entry into the database. While I am able to save the new row to the d ...

The loading of woff2, woff, and ttf files resulted in a 400 error

Can you explain why the woff2, woff, and ttf files in the "assets" folder are not loading? Any suggestions on how to fix this issue? https://i.sstatic.net/ZMsBw.jpg ...

Forever waiting: Angular HTTP requests stuck in limbo

Switching from MongoDB to MySQL for my Angular/NodeJS project has brought about some challenges, particularly with handling HTTP Requests. I have tried GET and POST requests, but GET always remains pending and eventually fails, while POST does not successf ...

Learn how to trigger an event or API call in Angular 8 when the browser is closed with the help of HostListener

I am facing the challenge of calling a simple websocket closure API when the browser is closed in my project. I attempted to utilize HostListener, but unfortunately it did not work as expected. You can find the code snippet below: https://stackblitz.com/ ...

Tips for creating a draggable Angular Material dialog

Has anyone been able to successfully implement draggable functionality in an Angular Material Dialog? I've spent a considerable amount of time searching for a definitive answer but have come up empty-handed. Any insights or guidance would be greatly a ...

Switching from a TypeOrm custom repository to Injectable NestJs providers can be a smooth transition with the

After updating TypeORM to version 0.3.12 and @nestjs/typeorm to version 9.0.1, I followed the recommended approach outlined here. I adjusted all my custom repositories accordingly, but simply moving dependencies into the providers metadata of the createTe ...

Oops! The program encountered an issue on the production environment, but it's running smoothly

When I execute Webpack using the command node node_modules/webpack/bin/webpack. js --env. prod An error message is displayed below. However, when running in --env. dev mode, the command executes without any issues. Can't resolve './../$$_gen ...

Issues arise when trying to update the modelValue in unit tests for Vue3 Composition API

Recently delving into Vue, I am currently engaged in writing unit tests for a search component incorporated in my project. Basically, when the user inputs text in the search field, a small X icon emerges on the right side of the input box. Clicking this X ...

The vertical lines separating the buttons are not evenly centered

I need help to center a vertical line between my buttons in the middle of the header. Currently, the line goes up and my disconnect button is not aligned properly. Can you assist me in creating a responsive design? Thank you. https://i.sstatic.net/XIeiQ4E ...