typescript 捕捉打字稿承诺中的错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40370399/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:59:08  来源:igfitidea点击:

catching errors in typescript promises

angulartypescripterror-handlingecmascript-6es6-promise

提问by rubmz

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:

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

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

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

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

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

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?

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

回答by Tiba

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

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

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

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

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

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

当一个承诺失败时,所有后续承诺都会被跳过并被catch调用。假如method2失败了,我们这个产业链的呼叫:method1 -> method2 -> handleError -> handleFinally

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

现在假设我们想忽略 中的错误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())

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

请注意,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())

回答by Fiddles

Have each promise return the nested promise, and the top promise have a .catch(..)

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