“UnhandledPromiseRejectionWarning” error even when

2019-05-14 07:58发布

问题:

So I have this code, createExampleDir is not yet implemented, so the test fails:

let chai    = require('chai');
let expect  = chai.expect;
let homeDir = require('home-dir');
let lib     = require('../lib.js');

chai.use(require('chai-fs'));

let dir     = homeDir('/example-dir');

describe('lib', () =>
  describe('createExampleDir', () =>
    it('should find ~/example-dir', () => lib.createExampleDir()
      .then(() => expect(dir).to.be.a.directory())
      .catch(() => {throw Error('Who cares!');})
    )
  )
);

The problem is that I'm getting an UnhandledPromiseRejectionWarning error, the error "Who cares!" is throw, so the catch happens:

(node:30870) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): [object Object] (node:30870) [DEP0018] 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 should I do to avoid the UnhandledPromiseRejectionWarning warning?

回答1:

add this code after chai.use

process.on('unhandledRejection', e => {
  console.error(e);
});

And you can catch error and code string number.