我目前使用的是 Angular 5.2.4。我最近意识到,如果未捕获到 promise 中抛出的异常/错误,它们就会消失。
我记得这曾经是 Promise 在以前版本的 angular 上的正常行为,但现在它应该显示如下内容:
Unhandled Promise rejection: exception message, etc.
现在,如果我使用这段代码(作为组件):
import { Component, OnInit } from "@angular/core";
@Component({
selector: "o-test-component",
template: "<button (click)='test()'>test button</button>",
styles: [""]
})
export class TestComponentComponent implements OnInit {
constructor() {}
ngOnInit() {}
test() {
console.log("testing ...");
const a = new Promise((resolve, reject) => {
reject("rejecting a");
});
a.then(() => console.log("test"));
console.log("test2");
const m = new Promise((resolve, reject) => {
throw new Error("throwing b");
});
console.log("end test");
}
}
我得到:
testing ...
test2
end test
当我单击该按钮时,不会记录此类“未捕获的异常”。
如果我直接在 chrome 控制台中复制 test()
方法内容,我会得到这些:
Unhandled Promise rejection: throwing b ; Zone: <root> ; Task: null ; Value: Error: throwing b
at Promise (<anonymous>:8:13)
at new ZoneAwarePromise (zone.js:875)
at <anonymous>:7:15 Error: throwing b
at Promise (<anonymous>:8:13)
at new ZoneAwarePromise (webpack-internal:///../../../../zone.js/dist/zone.js:875:29)
at <anonymous>:7:15
和
Unhandled Promise rejection: rejecting a ; Zone: <root> ; Task: Promise.then ; Value: rejecting a undefined
知道为什么组件中没有日志吗?这是正常的吗?或者也许我的项目中有某些东西阻止记录 promise 中抛出的未捕获异常?
我听说 bluebird 库可以解决这个问题,但现在它不应该用于此,因为日志记录应该是默认行为(现在 Promise 是原生的)
最佳答案
简答
嗯,出于某种原因,记录错误的文件 (core.js
) 被浏览器过滤了。后来看到了,不过右下角有个小“23隐藏”。左 Pane 还显示创建日志的所有文件。
要解决此问题:在 Chrome 控制台中,右键单击 -> 过滤器 -> 取消选中已过滤的文件。
其他线索
如果您卡在问题上而这不是您的解决方案,您可以阅读问题的评论并检查以下内容:
-检查多个浏览器。
-检查您是否正在为 Promise 使用 pollyfills。 Angular 5 的默认类是“ZoneAwarePromise”;使用 console.log(Promise) 来显示你的。
-检查它们是否在您使用此 stackblitz 时显示:stackblitz.com/edit/angular-kf8qdq
-检查您是否没有自定义错误处理程序:捕获“PromiseRejectionEvent”的东西
-如果您正在使用 ZoneAwarePromise
,您可以在 zone.js
中添加调试断点并检查 resolvePromise()
其中 如果错误添加到
代码。_uncaughtPromiseErrors
数组中,则使用 REJECTED_NO_CATCH
-还要检查 api.showUncaughtError()
是否返回 true(即使 api.onUnhandledError()
似乎没有被调用)
关于Angular Promise 不记录未捕获的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49790931/