在打字稿承诺中捕获错误

rub*_*bmz 3 error-handling typescript ecmascript-6 es6-promise angular

Angular2对于链式诺言具有非常有用的诺言错误捕获机制。但是,通常的情况(至少对我而言)是在前一个的解析处理程序中调用promise的情况。这是由于需要在开始下一个承诺之前处理信息。例如:

this.d( "facebookOAuthLogin() - starts" );
this.fbProvider.login().then(
    ( loginResponse: { status: string, authResponse: any, accessToken: string, expiresIn: string, session_key: string, sig: string, userID: string } ) =>
    {
        this.d( "facebookOAuthLogin() - fbProvider.login() succeeded" );
        Config.config.sessionToken = loginResponse.authResponse.accessToken;
        this.fbProvider.getCurrentUserProfile().then(
            ( profileData : { email: string, name: string } ) =>
            {
                this.d( "facebookOAuthLogin() - fbProvider.getCurrentUserProfile() succeeded" );
                Config.config.user_email = profileData.email;
                Config.config.user_name = profileData.name;
                this.fbProvider.getUserPicture().then(
                    ( pictureData : { data:{ is_silhouette: boolean, url: string, width: number, height: number } } ) =>
                        {
                            this.d( "facebookOAuthLogin() - fbProvider.getUserPicture() succeeded" );
                            // this.facebook_picture_url = pictureData.data.url;
                            // this.facebook_picture_is_silhouette = pictureData.data.is_silhouette;
                            if( pictureData.data.is_silhouette || pictureData.data.url == null )
                            {
                                this.d( "facebookOAuthLogin() - pictureData.data.url == null" );
                                Config.config.jpegBase64Data = null;
                                this.afterFacebookLogin();
                            }
                            else
                            {
                                this.d( "facebookOAuthLogin() - pictureData.data.url != null" );
                                ImageStore.readToData( pictureData.data.url ).then(
                                    dataBase64 =>
                                    {
                                        this.d( "facebookOAuthLogin() - facebook picture read successfully" );
Run Code Online (Sandbox Code Playgroud)

因此,问题是-如果我想以最简单的方式捕获所有处理程序中的所有错误(让我们省略异常的类型-假设我只需要记录错误并进行报告。任何错误-无需单独处理它们)

据我了解,在代码周围放置try {} catch(err)不会捕获Promise处理程序引发的错误。

使用上面的代码-是否需要在每个Promise处理程序中添加try / catch,还是可以使用外部(第一个)promise的.catch()方法?

Tib*_*iba 8

链接诺言的一种方法是在then函数内部返回诺言,如下所示:

method1()
  .then(response1 => {
    // ... do something
    return method2(response1);
  })
  .then(response2 => {
    // ... do something
    return method3(response3);
  })
  .catch(error => handleError(error))
  .finally(() => handleFinally())
Run Code Online (Sandbox Code Playgroud)

如预期的那样,当所有承诺均成功解决后,所有方法都将依次调用(method1 -> method2 -> method3 -> handleFinally)。

当一个承诺失败时,所有随后的承诺都将被跳过,catch而是被调用。假设method2失败,我们有以下调用链:method1 -> method2 -> handleError -> handleFinally

现在假设我们要忽略中的错误method2,我们可以为此调用添加catch语句:

method1()
  .then(response1 => {
    // ... do something
    return method2(response1)
      .catch(error2 => silentlyHandleError(error2));
  })
  .then(response2 => {
    // ... do something
    return method3(response3);
  })
  .catch(error => handleError(error))
  .finally(() => handleFinally())
Run Code Online (Sandbox Code Playgroud)

请注意,catch不得将“承诺”放在承诺的主链中。下一块说明更多:

method1()
  .then(response1 => {
    // ... do something
    return method2(response1);
  })
  .catch(error => silentlyHandleError(error)) // catchs error1 and error2
  .then(response2 => {
    // ... do something
    return method3(response3);
  })
  .catch(error => handleError(error))
  .finally(() => handleFinally())
Run Code Online (Sandbox Code Playgroud)