捕获Promise相关的错误

时间:2017-06-25 02:44:08

标签: javascript angular typescript

我是JavaScript Promsises的新手,所以我确信我做错了什么。您是否能够指出与使用Angular 2处理Java Script Promises相关的最佳实践。

以下是我用于身份验证的承诺:



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

                });*/
        });
&#13;
&#13;
&#13;

这是我的Angular 2组件Typescript,它没有捕获Promise错误:

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

例如,当Web API服务器不可用时,不会在Typescipt组件中捕获ERR_CONNECTION_REFUSED错误。我想告诉用户有连接问题

1 个答案:

答案 0 :(得分:1)

@Maximus指出了伟大的Angular相关参考,这帮助我实现了我的目标。这是一个有效的解决方案,以防有人寻找类似的东西:

&#39; authentication.service.ts&#39;:

&#13;
&#13;
    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);
    }
&#13;
&#13;
&#13;

&#39; .component.ts&#39;:

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