在打字稿承诺中捕获错误 [英] catching errors in typescript promises

查看:70
本文介绍了在打字稿承诺中捕获错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Angular2 has very useful promises error catching mechanism for chained promises. Yet, the usual case (at least for me) is that of promises called from within the resolve handler of the previous one. This is due to the need to process information prior to starting the next promise. For example:

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

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

So, the question is - If I want to catch all the errors in all the handlers in the simplest way (let's leave out the type of the exceptions - Assume I just need to log the error and report. Any error - Without handling them separatedly.)

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

From what I understand putting a try{}catch(err) around the code would not catch the errors thrown from the Promise handler.

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

With the code above - Do I need to add a try/catch in every Promise handler, or can I use the external (first) promise's .catch() method?

推荐答案

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

One way to chain promises is to return a promise inside then function, like this:

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

When all promises are successfully resolved, as expected, all methods are called sequentially (method1 -> method2 -> method3 -> handleFinally).

当一个承诺失败时,所有随后的承诺都将被跳过,而改为调用 catch .假设 method2 失败,我们有如下调用链: method1->方法2->handleError->最终.

When one promise fails, all subsequent are skipped and catch is invoked instead. Supposing method2 fails, we have this chain of calls: method1 -> method2 -> handleError -> handleFinally.

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

Now suppose we want to ignore the error in method2, we can add a catch statement for this call:

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 置于承诺的主链之中.下一块说明更多:

Notice that the catch must not be placed among the main chain of promises. The next block explains a little bit more:

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

这篇关于在打字稿承诺中捕获错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆