【问题标题】:error from service not being caught in component.ts服务错误未在 component.ts 中捕获
【发布时间】:2019-05-30 13:22:32
【问题描述】:

一旦用户登录,我就会检索他们的userAccount。在没有返回的情况下,我在服务中抛出错误。然后我继续在component.ts 控制器中捕获错误。

由于某种原因,component.ts 没有捕捉到抛出的错误。在控制台中,我可以看到错误,但由于某种原因,我的 component.ts 没有在 try/catch 块中捕获它。

我已经测试了很多次,看看它失败的地方,似乎错误消息没有到达catch语句。

这是我的服务:

/* On error: */
error => {

    if (error.status === 401) {

        Helpers.logGroupedErrorObjectsToDevConsole(
            'Login Service: getCustomerAccount()',
            [
                {
                    title: 'Session Timed Out:',
                    info:  true
                }
            ]
        );
    } else {
        Helpers.logGroupedErrorObjectsToDevConsole(
            'Login Service: getCustomerAccount()',
            [
                {
                    title: 'Cannot get customer account:',
                    info: true
                }
            ]
        );
    }

    throw new Error(error);
}

这是我的component.ts

try {
        setTimeout(() => {
           this._service.customer(this.url, this.route)
        }, 1000);
     } catch (e) { 
         this.showUnknownLoginFailureMessage  = true;
     }

我期望在 component.ts 中处理错误

有可能吗? 我是在正确处理错误还是遗漏了什么?

我需要一些指导。

提前致谢!

【问题讨论】:

    标签: angular typescript service error-handling


    【解决方案1】:

    try/catch 不会在传递给订阅的回调中捕获任何内容(或 然后,或 setTimeout 或任何类似的东西)运行在不同的 “滴答”或“微任务”。你必须在他们所在的任务中捕获错误 发生了。

    这个答案https://stackoverflow.com/a/50494803/7179294有解决办法

    【讨论】:

      【解决方案2】:

      您可以通过将try... catch 语句移动到setTimeout 回调中来处理异常:

      setTimeout(() => {
        try {
          this._service.customer(this.url, this.route);
        } catch (e) {
          this.showUnknownLoginFailureMessage  = true;
        }
      }, 1000);
      

      请参阅this stackblitz 以获取演示。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-06
        • 2015-11-01
        • 2013-07-04
        • 2021-07-12
        • 1970-01-01
        • 2018-01-27
        相关资源
        最近更新 更多