【问题标题】:Angular Promise not logging uncaught exceptionAngular Promise 未记录未捕获的异常
【发布时间】:2018-11-22 22:49:10
【问题描述】:

我目前正在使用 Angular 5.2.4。我最近意识到,promise 中抛出的异常/错误在没有被捕获时就会消失。

我记得这曾经是 Promise 在以前版本的 angular 上的正常行为,但现在它应该显示如下内容:

未处理的 Promise 拒绝:异常消息等

现在,如果我使用这段代码(作为组件):

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");
  }
}

我明白了:

测试 ...

测试2

结束测试

当我单击按钮时,不会记录此类“未捕获的异常”。

如果我直接在 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

知道为什么组件中没有日志吗?这是正常的吗?或者也许我的项目中有一些东西可以防止记录承诺中抛出的未捕获异常?

我听说 bluebird 库可以解决这个问题,但现在不应该使用它,因为日志记录应该是默认行为(现在 Promise 是原生的)

【问题讨论】:

  • Angular 应该记录未捕获的异常。在此处查看堆栈闪电战:stackblitz.com/edit/angular-kf8qdq 您在项目中有自定义的 ErrorHandler 吗?您可以通过搜索 ErrorHandler 的引用找到此内容
  • @nipuna777 是的,这是我所期待的行为。不幸的是,我的项目中没有 ErrorHandler。
  • 您是否检查过可能导致此问题的软件包?
  • 你可能使用了一个糟糕的 promise polyfill,你能console.log(Promise) 告诉我们它记录了什么吗?
  • “我听说 bluebird 库可以解决这个问题,但现在不应该使用它,因为日志记录应该是默认行为(现在 Promise 是原生的)” - 作为bluebird 维护者和其中一名相关人员我可以确认是这种情况。

标签: angular exception promise angular5


【解决方案1】:

简答

好吧,由于某种原因,记录错误的文件 (core.js) 被浏览器过滤掉了。后来看到了,但是右上角有个小“23隐藏”。左窗格还显示创建日志的所有文件。

要解决这个问题:在 Chrome 控制台中,右键单击 -> 过滤器 -> 取消选中已过滤的文件。

其他线索

如果您遇到问题并且这不是您的解决方案,您可以阅读问题的 cmets 并检查以下内容:

-检查多个浏览器。

-检查你是否在 Promise 中使用 pollyfills。角度 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() 似乎没有被调用)

【讨论】:

    猜你喜欢
    • 2010-11-08
    • 1970-01-01
    • 2021-10-05
    • 1970-01-01
    • 2011-09-08
    • 2015-03-16
    • 2018-01-14
    • 2019-04-28
    • 1970-01-01
    相关资源
    最近更新 更多