handle any errors related to Promises

My journey with JavaScript Promises has just begun, and I'm certain that there are better ways to handle them. Could you share some best practices for dealing with JavaScript Promises in the context of Angular 2?

Below is my Promise implementation used for authentication:

    authenticate(user: Object): Promise<any> {
        return new Promise((resolve, reject) => {
            let body = JSON.stringify({ email: user['email'], password: user['passwords']['password'], repeatPassword: user['passwords']['repeatPassword'] });
            let headers = new Headers({ 'Content-Type': 'application/json' });
            let options = new RequestOptions({ headers: headers });

            return this.http.post(`${this.webApiService.webServiceAddressIp}/users/register`, body, options)
                .subscribe((response: Response) => {
                    // login successful if there's a jwt token in the response
                    console.log("worked");
                    let user = response.json();
                    if (user && user.token) {
                        this.setSession(user.token);
                    }

                    return user;
                }
                , (error: any) => {
                    console.log("xxxxxxerror");
                    return error;
                });
                /*() => {

                });*/
        });

Here is an excerpt from my Angular 2 component TypeScript code where Promise errors are not being caught effectively:

      this.authenticationService.authenticate(values).then((val: string) => {
        console.log("done");
      }).catch((err) => {
        // Re-throw the error as a higher-level error.
        // We will include the message from the lower-level 
        // error as part of the error message for this error.
        console.log('11111');
      })
        .catch((err) => {
          // In here we will get the higher-level error.
          console.log("22222");
        });

For instance, when the web API server is unavailable, ERR_CONNECTION_REFUSED errors are not handled properly within the TypeScript component. It would be ideal to inform the user about the connection issue.

Answer №1

@Maximus shared a valuable Angular reference that guided me to achieve my goal successfully. Below is the solution I implemented for those seeking something similar:

'authentication.service.ts':

    private extractData(res: Response) {
        let body = res.json();
        return body.data || {};
    }

    private handleError(error: Response | any) {
        // You might consider using remote logging infrastructure in a real-world app
        let errMsg: string;
        if (error instanceof Response) {
            const body = error.json() || '';
            const err = body.error || JSON.stringify(body);
            errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
        } else {
            errMsg = error.message ? error.message : error.toString();
        }
        console.error(errMsg);
        return Observable.throw(errMsg);
    }

    authenticate(user: Object): Observable<any> {

        let body = JSON.stringify({ email: user['email'], password: user['passwords']['password'], repeatPassword: user['passwords']['repeatPassword'] });
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });

        return this.http.post(`${this.webApiService.webServiceAddressIp}/users/register`, body, options)
            .map(this.extractData)
            .catch(this.handleError);
    }

'.component.ts':

  public onSubmit(values: Object): void {
    this.submitted = true;
    if (this.form.valid) {
      this.showSpinner = true;

      this.authenticationService.authenticate(values)
        .subscribe(
        user => this.user = user,
        error => this.errorMessage = "Error Occurred");
    }
  }

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

Storing object dimensions in react-redux

Are there any performance issues associated with storing a large number of items in the redux-store? For example, if the store structure looks like this: { user:{...}, userDetail:{}, shoppingCart:{}, OrderDetail:{}, ... } The store co ...

The template is displaying the string as "[object Object]"

I've implemented code in my ngOnInit function to fetch the translation for a specific text. The following function is being called: async getEmailTranslation() { const email$ = this.translate.get('SUPPORT_TRANSLATE.EMAIL'); this.emai ...

Angular component nesting involves placing one component within another component in

When a component is nested inside another, what is that called? For example: <agm-map [latitude]="lat" [longitude]="lng"> <agm-marker [latitude]="lat" [longitude]="lng"></agm-marker> </agm-map> Can you explain how this nesting w ...

Selecting multiple rows on a Lazily Loaded jQuery Datatable

Currently, I am utilizing a lazy loaded (Deferred) jQuery Datatable and attempting to implement multi-row selection. However, every time I switch to another page of the datatable, the selected rows from the previous page get cleared. // Here's how yo ...

Troubleshooting Problems with Displaying and Concealing Images Using JavaScript

Currently, I am attempting to create a show/hide button that toggles all the images on the page on and off using getElementsByClassName. Initially, my code looked like this: if (document.getElementsByClassName('showHide').style.visibility =&apos ...

JavaScript makes it simple to display student names based on their ID numbers

Here is my JavaScript code: <script language="Javascript"> var data = { 7: "Jack Black", 8: "John Smith" }; var id = document.getElementById("id"), emp = document.getElementById("name"); id.addEventListener("keyup", function() { emp.value ...

What are the best practices for creating and displaying functional components effectively?

I'm in the process of building and displaying a functional component following the guidelines provided as a starting point. After reviewing the instructions, it seems like I should be able to achieve something similar to this: class MyComponent exten ...

Creating a dynamic user interface in Angular 6 that successfully tracks changes without reliance on the parent

As I delve into the world of Angular, I am faced with a challenge in creating a reusable component that will be bundled into an npm module. The issue lies in the UI change detection aspect. In order for the component to function properly, the application ...

Eliminate the hazy white layer covering the exterior of an image that has been blurred using CSS

Hey there, I've encountered an issue with an image that transitions from blurred to unblurred when the dom is loaded. <div class="image-wrapper-container2"><div class="image-wrapper orig" style="background-image: url('https://www.w3scho ...

Find out the device's brand, type, storage capacity, and color

Can we identify the Make, Model, Capacity, and Color of a mobile device using React JS? Many existing node modules only detect the make and model. Is it feasible to also detect Capacity and Color? For example, Apple iPhone 11 Pro 64GB in Black. ...

Upon page initialization, VueJS namespaced Vuex module getter does not properly return the expected value

Even in identical situations, I am receiving different outputs from the same getter function. console.log(store.getters); When checking the console, I see: {}: auth/loggedIn: true, which is the correct value. However, when specifically accessing this get ...

Issue with VueJS 2 and TypeScript: computed value unable to recognize property specified in data object

When creating the following component: <template lang="html"> <div> <p>{{ bar }}</p> </div> </template> <script lang="ts"> import Vue from 'vue'; export const FooBar = Vue.ex ...

Adding a specified number to a value in React: x + y

I am facing an issue with adjusting the value of deliveryFee based on the changing value of a variable weight. Initially, I have set specific values for deliveryFee based on different weight ranges: Up to 2 kg => $3.40 Up to 5 kg => $3.80 Up to 10 k ...

Using a straightforward approach with v-model in vue.js on an href element instead of a select

Is there a way to utilize an href-link instead of using <select> to switch languages with vue.i18n? <a @click="$i18n.locale = 'en'">EN</a> <a @click="$i18n.locale = 'da'">DA</a> ...

Ways to prevent altering values in ngModel

I am working on a component in Angular 5 where I am trying to write unit tests to ensure that when the component is disabled, it should not be possible to set a value to its model. However, even after disabling it, I am still able to change the value. [ ...

Nested Angular Router Resolvers

I need help with a routing issue: const routes: Routes = [ { path: ':id', component: MoyComponent, resolve: { first: MyFirstResolver second: mySecondResolver(first) } } Here is the ...

Exclude the key-value pair for any objects where the value is null

Is there a way to omit one key-value pair if the value is null in the TypeScript code snippet below, which creates a new record in the Firestore database? firestore.doc(`users/${user.uid}`).set({ email: user.email, name: user.displayName, phone: ...

Angular 6 Subscription Service Does Not Trigger Data Sharing Events

Is there a way to set a value in one component (Component A) and then receive that value in another component (Component B), even if these two components are not directly connected as parent and child? To tackle this issue, I decided to implement a Shared ...

Instructions for creating a function in TypeScript that accepts an array as user input and determining its length

Looking to develop a TypeScript function that can take an array of any type as input, calculate the number of elements present in it, and return the count. An example output would be: If user inputs: ["soccer", "basketball"] Then output: 2 Any suggestion ...

`Is it possible to execute page.screenshot within page.evaluate using Puppeteer?`

I am currently working on a web scraping project that involves extracting content from a webpage and capturing a screenshot of it. I have been using Puppeteer for this task, but I have encountered a problem. Whenever I try to call a function that includes ...