angular - 服务错误未在 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 中处理错误
是否可以?我是在正确处理错误还是遗漏了什么?
我需要一些指导。
提前致谢!
解决方案
try/catch 不会在传递给 subscribe 的回调中捕获任何内容(或者 then,或setTimeout或任何类似的东西),它在不同的“tick”或“microtask”上运行。您必须在发生错误的任务中捕获错误。
这个答案中有一个解决方案https://stackoverflow.com/a/50494803/7179294
推荐阅读
- laravel - 每当 LARAVEL 中发生任何更新时发送通知
- node.js - 将 API 中的 EC2 容器中的图像发送到前端应用程序
- keycloak - 如何在访问令牌中显示客户端角色属性
- c# - ReportViewer 显示空行
- mongodb - Mongoose 错误:不支持“useCreateIndex”,但文档仍然有它
- javascript - preventDefault、stopPropagation 和 cancelBubble 不足以阻止 contextMenu 尝试在 Firefox 移动测试视图中打开
- r - 当最大数据在ggplot2中没有达到那么高时,有没有办法强制箱线图以连续比例显示所有数字
- postgresql - Docker 从 yml postgres 数据库 url 错误组成
- docker - Docker Compose:将输出记录到文件和标准输出
- sql - 按问题分组 GreenPlum