如何访问通过 addEventListener 添加的 XMLHttpRequest 错误?

How to get access to the XMLHttpRequest errors added via addEventListener?

我正在尝试但没有找到方法。

想做这件事很奇怪,但如果你不得不这样做,你可以使用 monkeypatch XMLHttpRequest.prototype.addEventListener:

const errorHandlers = [];
XMLHttpRequest.prototype.addEventListener = function(...args) {
  if (args[0] === 'error') {
    errorHandlers.push(args[1]);
  }
  return EventTarget.prototype.addEventListener.apply(this, args);
};

const x = new XMLHttpRequest();
x.addEventListener('error', () => console.log('handle error'));

console.log(errorHandlers);

确保在调用 addEventListener 的代码运行之前 修补 addEventListener