Skip to content

Commit

Permalink
improve interoperability of custom Errors (#5752)
Browse files Browse the repository at this point in the history
closes #5751
  • Loading branch information
alexlamsl authored Dec 1, 2022
1 parent 574ca47 commit 59e3855
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 13 deletions.
5 changes: 2 additions & 3 deletions lib/parse.js
Original file line number Diff line number Diff line change
Expand Up @@ -207,11 +207,10 @@ function JS_Parse_Error(message, filename, line, col, pos) {
this.line = line;
this.col = col;
this.pos = pos;
configure_error_stack(this, new SyntaxError(message, filename, line, col));
}
JS_Parse_Error.prototype = Object.create(Error.prototype);
JS_Parse_Error.prototype = Object.create(SyntaxError.prototype);
JS_Parse_Error.prototype.constructor = JS_Parse_Error;
JS_Parse_Error.prototype.name = "SyntaxError";
configure_error_stack(JS_Parse_Error);

function js_error(message, filename, line, col, pos) {
throw new JS_Parse_Error(message, filename, line, col, pos);
Expand Down
25 changes: 15 additions & 10 deletions lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,28 +55,33 @@ function find_if(func, array) {
for (var i = array.length; --i >= 0;) if (func(array[i])) return array[i];
}

function configure_error_stack(fn) {
Object.defineProperty(fn.prototype, "stack", {
function configure_error_stack(ex, cause) {
var stack = ex.name + ": " + ex.message;
Object.defineProperty(ex, "stack", {
get: function() {
var err = new Error(this.message);
err.name = this.name;
try {
throw err;
} catch (e) {
return e.stack;
if (cause) {
cause.name = "" + ex.name;
stack = "" + cause.stack;
var msg = "" + cause.message;
cause = null;
var index = stack.indexOf(msg);
if (index >= 0) index += msg.length;
index = stack.indexOf("\n", index) + 1;
stack = stack.slice(0, index) + stack.slice(stack.indexOf("\n", index) + 1);
}
}
return stack;
},
});
}

function DefaultsError(msg, defs) {
this.message = msg;
this.defs = defs;
configure_error_stack(this, new Error(msg));
}
DefaultsError.prototype = Object.create(Error.prototype);
DefaultsError.prototype.constructor = DefaultsError;
DefaultsError.prototype.name = "DefaultsError";
configure_error_stack(DefaultsError);

function defaults(args, defs, croak) {
if (croak) for (var i in args) {
Expand Down

0 comments on commit 59e3855

Please sign in to comment.