首页 > 解决方案 > 服务错误未在 component.ts 中捕获

问题描述

用户登录后,我会检索他们的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 中处理错误

是否可以?我是在正确处理错误还是遗漏了什么?

我需要一些指导。

提前致谢!

标签: angulartypescriptserviceerror-handling

解决方案


try/catch 不会在传递给 subscribe 的回调中捕获任何内容(或者 then,或setTimeout或任何类似的东西),它在不同的“tick”或“microtask”上运行。您必须在发生错误的任务中捕获错误。

这个答案中有一个解决方案https://stackoverflow.com/a/50494803/7179294


推荐阅读