Skip to content

Commit

Permalink
[Fix] throws: avoid crashing on a nonconfigurable or nonextensible …
Browse files Browse the repository at this point in the history
…`expected`
  • Loading branch information
ljharb committed Jan 15, 2023
1 parent 834453c commit 0731b5f
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 7 deletions.
10 changes: 6 additions & 4 deletions lib/test.js
Expand Up @@ -542,10 +542,12 @@ Test.prototype['throws'] = function (fn, expected, msg, extra) {
fn();
} catch (err) {
caught = { error: err };
if (Object(err) === err && (!isEnumerable(err, 'message') || !has(err, 'message'))) {
var message = err.message;
delete err.message;
err.message = message;
if (Object(err) === err && 'message' in err && (!isEnumerable(err, 'message') || !has(err, 'message'))) {
try {
var message = err.message;
delete err.message;
err.message = message;
} catch (e) { /**/ }
}
}

Expand Down
43 changes: 40 additions & 3 deletions test/throws.js
Expand Up @@ -176,10 +176,19 @@ tap.test('failures', function (tt) {
' at Test.<anonymous> ($TEST/throws.js:$LINE:$COL)',
' [... stack stripped ...]',
' ...',
'# non-extensible throw match',
'ok 15 error is non-extensible',
'ok 16 non-extensible error matches',
'ok 17 errorWithMessage is non-extensible',
'ok 18 non-extensible error with message matches',
'# frozen `message` property',
'ok 19 error is non-writable',
'ok 20 error is non-configurable',
'ok 21 non-writable error matches',
'',
'1..14',
'# tests 14',
'# pass 4',
'1..21',
'# tests 21',
'# pass 11',
'# fail 10',
''
]);
Expand Down Expand Up @@ -221,4 +230,32 @@ tap.test('failures', function (tt) {
t['throws'](function () { throw actual; }, TypeError, 'throws actual');
t.end();
});

test('non-extensible throw match', { skip: !Object.seal }, function (t) {
var error = { foo: 1 };
Object.seal(error);
t.throws(function () { error.x = 1; }, TypeError, 'error is non-extensible');

t.throws(function () { throw error; }, error, 'non-extensible error matches');

var errorWithMessage = { message: 'abc' };
Object.seal(errorWithMessage);
t.throws(function () { errorWithMessage.x = 1; }, TypeError, 'errorWithMessage is non-extensible');

t.throws(function () { throw errorWithMessage; }, error, 'non-extensible error with message matches');

t.end();
});

test('frozen `message` property', { skip: !Object.defineProperty }, function (t) {
var error = { message: 'abc' };
Object.defineProperty(error, 'message', { configurable: false, enumerable: false, writable: false });

t.throws(function () { error.message = 'def'; }, TypeError, 'error is non-writable');
t.throws(function () { delete error.message; }, TypeError, 'error is non-configurable');

t.throws(function () { throw error; }, { message: 'abc' }, 'non-writable error matches');

t.end();
});
});

0 comments on commit 0731b5f

Please sign in to comment.