1'use strict'; 2// Flags: --expose-gc 3 4const common = require('../../common'); 5const assert = require('assert'); 6const theError = new Error('Some error'); 7 8// The test module throws an error during Init, but in order for its exports to 9// not be lost, it attaches them to the error's "bindings" property. This way, 10// we can make sure that exceptions thrown during the module initialization 11// phase are propagated through require() into JavaScript. 12// https://github.com/nodejs/node/issues/19437 13const test_exception = (function() { 14 let resultingException; 15 try { 16 require(`./build/${common.buildType}/test_exception`); 17 } catch (anException) { 18 resultingException = anException; 19 } 20 assert.strictEqual(resultingException.message, 'Error during Init'); 21 return resultingException.binding; 22})(); 23 24{ 25 const throwTheError = () => { throw theError; }; 26 27 // Test that the native side successfully captures the exception 28 let returnedError = test_exception.returnException(throwTheError); 29 assert.strictEqual(returnedError, theError); 30 31 // Test that the native side passes the exception through 32 assert.throws( 33 () => { test_exception.allowException(throwTheError); }, 34 (err) => err === theError 35 ); 36 37 // Test that the exception thrown above was marked as pending 38 // before it was handled on the JS side 39 const exception_pending = test_exception.wasPending(); 40 assert.strictEqual(exception_pending, true, 41 'Exception not pending as expected,' + 42 ` .wasPending() returned ${exception_pending}`); 43 44 // Test that the native side does not capture a non-existing exception 45 returnedError = test_exception.returnException(common.mustCall()); 46 assert.strictEqual(returnedError, undefined, 47 'Returned error should be undefined when no exception is' + 48 ` thrown, but ${returnedError} was passed`); 49} 50 51{ 52 // Test that no exception appears that was not thrown by us 53 let caughtError; 54 try { 55 test_exception.allowException(common.mustCall()); 56 } catch (anError) { 57 caughtError = anError; 58 } 59 assert.strictEqual(caughtError, undefined, 60 'No exception originated on the native side, but' + 61 ` ${caughtError} was passed`); 62 63 // Test that the exception state remains clear when no exception is thrown 64 const exception_pending = test_exception.wasPending(); 65 assert.strictEqual(exception_pending, false, 66 'Exception state did not remain clear as expected,' + 67 ` .wasPending() returned ${exception_pending}`); 68} 69