angular - 捕获 typescript promise 中的错误

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

Angular2 为链式 promise 提供了非常有用的 promise 错误捕获机制。然而,通常的情况(至少对我而言)是从前一个的解析处理程序中调用的 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() 方法吗?

最佳答案

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

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

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

当一个 promise 失败时,将跳过所有后续 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 的主链中。下一个 block 解释得更多一点:

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

关于angular - 捕获 typescript promise 中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40370399/

相关文章:

node.js - 虚拟助手机器人框架和控制库

javascript - 在 Angular2 中使用动态组件时出现错误 "ERROR TypeError: Cannot read property ' createComponent' of undefined"

javascript - 使用 index.ts 导出 'default'

rest - CakePHP 3.x REST API-调试关闭时的自定义错误消息

javascript - 如何从控制台获取信息

依赖于另一个表单控件的 Angular 2 自定义验证器

Angular EventEmitter 与通过服务进行通信

jquery - ASP.NET AJAX页面方法不一致

angular - SweetAlert 与 Angular 7

angular - Webpack 从模块导入的类不是构造函数