lucas
lucas

Reputation: 4685

catch Promise related errors

I am new to JavaScript Promsises, so I am sure I am doing something wrong. Would you be able to point out what are best practices related to handling Java Script Promises with Angular 2.

Here is my Promise 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;
                });
                /*() => {

                });*/
        });

And here is my Angular 2 component Typescript that does not catch Promise errors:

      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");
        });

As an example, when web API server is unavailable, ERR_CONNECTION_REFUSED error are not being caught within Typescipt component. I would like to tell User there was a connection problem

Upvotes: 1

Views: 74

Answers (1)

lucas
lucas

Reputation: 4685

@Maximus has pointed out great Angular related reference, that has helped me to achieve what I was after. Here is a working solution in case someone will be looking for similar:

'authentication.service.ts':

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

    private handleError(error: Response | any) {
        // In a real world app, you might use a remote logging infrastructure
        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 Occured");
    }
  }

Upvotes: 1

Related Questions