【问题标题】:catching errors in typescript promises捕捉打字稿承诺中的错误
【发布时间】:2017-03-15 04:50:43
【问题描述】:

Angular2 为链式 Promise 提供了非常有用的 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" );

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

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

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

【问题讨论】:

    标签: angular typescript error-handling ecmascript-6 es6-promise


    【解决方案1】:

    链接 Promise 的一种方法是在 then 函数中返回一个 Promise,如下所示:

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

    当所有承诺都成功解决后,如预期的那样,所有方法都会按顺序调用 (method1 -> method2 -> method3 -> handleFinally)。

    当一个promise 失败时,所有后续都被跳过,而是调用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())
    

    注意catch不能放在promise的主链中。下一块解释更多:

    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())
    

    【讨论】:

      【解决方案2】:

      让每个 promise 返回嵌套的 promise,并且顶部的 promise 有一个 .catch(..)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-21
        • 1970-01-01
        • 2020-11-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多