简体   繁体   English

在Node.js 7中,什么是压缩UnhandledPromiseRejectionWarning的正确方法?

[英]In Node.js 7 what is the proper way to suppress UnhandledPromiseRejectionWarning?

In Node.js I have a module which consists of just one function. 在Node.js中,我有一个只包含一个函数的模块。 The function returns promise and the promise could be rejected. 该函数返回promise并且可以拒绝promise。 Still I don't want to force all users of the module to handle the rejection explicitly. 我仍然不想强制模块的所有用户明确地处理拒绝。 By design in some cases it makes sense to just ignore the returned promise. 在某些情况下,通过设计,忽略返回的promise是有意义的。 Also I don't want to take the ability to handle the promise rejection away from module users. 此外,我不希望能够处理远离模块用户的承诺拒绝。

What is the way to properly do so? 正确的方法是什么?

After upgrading to Node.js 7.1.0 all my unit tests which ignore rejection handling show the following warning: 升级到Node.js 7.1.0后,忽略拒绝处理的所有单元测试都显示以下警告:

(node:12732) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: try to throw an error from unit test
(node:12732) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

What is the proper way to prevent termination of Node.js process in the future mentioned in DeprecationWarning description? DeprecationWarning描述中提到的防止将来终止Node.js进程的正确方法是什么?

If you're concerned about unhandled rejections causing your Nodejs process to terminate unintentionally in the future, you could register an event handler for the 'unhandledRejection' event on the process object. 如果您担心未处理的拒绝会导致Nodejs进程在将来无意中终止,您可以在process对象上为“unhandledRejection”事件注册事件处理程序。

process.on('unhandledRejection', (err, p) => {
  console.log('An unhandledRejection occurred');
  console.log(`Rejected Promise: ${p}`);
  console.log(`Rejection: ${err}`);
});

Edit 编辑

If you want the implementing user of your module to decide whether or not to handle the error in their code, you should just return your promise to the caller. 如果您希望模块的实现用户决定是否在其代码中处理错误,您应该将您的承诺返回给调用者。

yourModule.js yourModule.js

function increment(value) {
  return new Promise((resolve, reject) => {
    if (!value)
      return reject(new Error('a value to increment is required'));                  

    return resolve(value++);
  });
}

theirModule.js theirModule.js

const increment = require('./yourModule.js');

increment()
  .then((incremented) => {
    console.log(`Value incremented to ${incremented}`);
  })
  .catch((err) => {
    // Handle rejections returned from increment()
    console.log(err);
  });

In general, using a custom library like bluebird you can suppress rejections just from your code but nowhere else. 通常,使用像bluebird这样的自定义库,您可以仅通过代码来抑制拒绝,而不是其他任何地方。 Native promises can't do this yet. 本土承诺还不能做到这一点。

You can however manually suppress a promise by adding a catch handler for it. 但是,您可以通过为其添加catch处理程序来手动抑制promise。

 function yourExportedFunction() {
     const p = promiseThatMightRejectFn(); 
     p.catch(() => {}); // add an empty catch handler
     return p;
 }

This way you are explicitly ignoring the rejection from the promise so it is no longer an unhandled rejection just a suppressed one. 这样你就明确地忽略了对promise的拒绝,所以它不再是一个未处理的拒绝,只是一个被压制的拒绝。

This is not your problem to fix. 这不是你需要解决的问题。

Just use promises the way they were intended. 只需按照预期的方式使用承诺。 If the end user doesn't want to handle all rejections then THEY have to add an unhandledRejection handler. 如果最终用户不想处理所有拒绝,那么他们必须添加一个unhandledRejection处理程序。 Otherwise they will need to add catches. 否则他们将需要添加捕获量。

If your errors truly aren't breaking then you shouldn't be rejecting on them. 如果您的错误确实没有破裂,那么您不应该拒绝它们。 Just resolve with an error value. 只需使用错误值解决。 eg: 例如:

Success: resolve({result, error:null}) 成功: resolve({result, error:null})

Failure: resolve({result:null, error}) 失败: resolve({result:null, error})

It's still better to just reject and leave the end user to decide how to handle it. 最好拒绝并让最终用户决定如何处理它。

I can't figure out any way to do what you're describing. 我无法弄清楚你所描述的任何方式。

If you don't care about passing errors to your users, you can add a dummy catch block on the end of your promise chain: 如果您不关心向用户传递错误,可以在promise链的末尾添加一个虚拟catch块:

Promise.reject('foo')
.catch(() => {})

This will silence the warning, but won't allow your users to handle the error. 这将使警告静音,但不允许用户处理错误。

Perhaps you could add an option that your users could decide if they want to handle the error or not. 也许您可以添加一个用户可以决定是否要处理错误的选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM