标签: unhandled-promise-rejection

为什么“unhandledrejection”无法捕获 JSON.parse() 的错误?

我尝试从 抛出一个错误JSON.parse(),我希望“unhandledrejection”事件会捕获它:

window.addEventListener('unhandledrejection', event => {
  console.log('unhandledrejection:', event.reason?.message || event.reason);
});

Promise.resolve("{")
  .then((data) => {
    JSON.parse(data)
  });
Run Code Online (Sandbox Code Playgroud)

但是(Chrome 的)控制台中出现 Uncaught (承诺):

Uncaught (in promise) SyntaxError: Unexpected end of JSON input
  at JSON.parse (<anonymous>)
  ...
Run Code Online (Sandbox Code Playgroud)

我尝试了更多抛出错误的方法,它们都可以被捕获:

Uncaught (in promise) SyntaxError: Unexpected end of JSON input
  at JSON.parse (<anonymous>)
  ...
Run Code Online (Sandbox Code Playgroud)

我试图重新抛出错误,但它仍然无法被“unhandledrejection”捕获:

window.addEventListener('unhandledrejection', event => {
  console.log('unhandledrejection:', event.reason?.message || event.reason);
});

Promise.resolve("{")
  .then((data) => {
    eval(data)
  }); // unhandledrejection: SyntaxError: Unexpected end of input

Promise.resolve()
  .then(() => {
    throw 123
  }); …
Run Code Online (Sandbox Code Playgroud)

javascript promise unhandled-promise-rejection

6
推荐指数
0
解决办法
717
查看次数

ESLint 可以帮助您防止未处理的承诺拒绝吗?

eslint 是否有能力警告防止未处理的承诺拒绝的地方?

不推荐使用未处理的承诺拒绝。将来,未处理的承诺拒绝将使用非零退出代码终止 Node.js 进程。- DEP0018

你知道吗,我有点喜欢引擎目前处理 Unhandled-Promise-Rejections 的方式;因为当您遇到 Unhandled-Promise-Rejection 时,您的整个服务不会崩溃,而是会继续运行,并且只有依赖于错误承诺实例的部分无法完成。假设错误是由程序员在验证期间未预料到的某些用户输入引起的。有异常的异步函数继续服务于其他调用(那些没有相同的意外用户输入的调用)。是的,此时程序中存在垃圾,以永远等待永远无法解决的等待的形式,但对我来说,这比让服务完全崩溃更强大。

无论如何,我想其他人已经决定完美比稳健更重要。

因此,是时候让我的代码变得丑陋和完美了,.catch(()=>{});在我之前看起来像 MOP&GLOW 一样干净的代码中的所有等待之后不久附加。

ESlint 是否提供任何帮助我在没有捕获的情况下定位承诺的东西?是否有任何规范添加正在进行中,以解决这种丑陋和不便?

就个人而言,我希望我可以将引擎配置为仅终止来自 UnhandledPromiseRejection 的承诺链中的代码。我当然希望比将所有这些添加.catch(()=>{})到我等待的所有异步函数调用中更容易解决这个问题。

javascript node.js custom-error-handling ecmascript-next unhandled-promise-rejection

2
推荐指数
2
解决办法
1882
查看次数