1'use strict';
2
3const common = require('../common');
4const Countdown = require('../common/countdown');
5const assert = require('assert');
6
7// Verify that unhandled rejections always trigger uncaught exceptions instead
8// of triggering unhandled rejections.
9
10const err1 = new Error('One');
11const err2 = new Error(
12  'This error originated either by throwing ' +
13  'inside of an async function without a catch block, or by rejecting a ' +
14  'promise which was not handled with .catch(). The promise rejected with the' +
15  ' reason "null".'
16);
17err2.code = 'ERR_UNHANDLED_REJECTION';
18Object.defineProperty(err2, 'name', {
19  value: 'UnhandledPromiseRejection',
20  writable: true,
21  configurable: true
22});
23
24const errors = [err1, err2];
25const identical = [true, false];
26
27const ref = new Promise(() => {
28  throw err1;
29});
30// Explicitly reject `null`.
31Promise.reject(null);
32
33process.on('warning', common.mustNotCall('warning'));
34// If we add an unhandledRejection handler, the exception won't be thrown
35// process.on('unhandledRejection', common.mustCall(2));
36process.on('rejectionHandled', common.mustNotCall('rejectionHandled'));
37process.on('exit', assert.strictEqual.bind(null, 0));
38
39const timer = setTimeout(() => console.log(ref), 1000);
40
41const counter = new Countdown(2, () => {
42  clearTimeout(timer);
43});
44
45process.on('uncaughtException', common.mustCall((err, origin) => {
46  counter.dec();
47  assert.strictEqual(origin, 'unhandledRejection', err);
48  const knownError = errors.shift();
49  assert.deepStrictEqual(err, knownError);
50  // Check if the errors are reference equal.
51  assert(identical.shift() ? err === knownError : err !== knownError);
52}, 2));
53