improve interoperability of custom Errors (#5752)

closes #5751
This commit is contained in:
Alex Lam S.L
2022-12-01 21:54:00 +02:00
committed by GitHub
parent 574ca47666
commit 59e385591c
2 changed files with 17 additions and 13 deletions

View File

@@ -207,11 +207,10 @@ function JS_Parse_Error(message, filename, line, col, pos) {
this.line = line; this.line = line;
this.col = col; this.col = col;
this.pos = pos; 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.constructor = JS_Parse_Error;
JS_Parse_Error.prototype.name = "SyntaxError";
configure_error_stack(JS_Parse_Error);
function js_error(message, filename, line, col, pos) { function js_error(message, filename, line, col, pos) {
throw new JS_Parse_Error(message, filename, line, col, pos); throw new JS_Parse_Error(message, filename, line, col, pos);

View File

@@ -55,28 +55,33 @@ function find_if(func, array) {
for (var i = array.length; --i >= 0;) if (func(array[i])) return array[i]; for (var i = array.length; --i >= 0;) if (func(array[i])) return array[i];
} }
function configure_error_stack(fn) { function configure_error_stack(ex, cause) {
Object.defineProperty(fn.prototype, "stack", { var stack = ex.name + ": " + ex.message;
Object.defineProperty(ex, "stack", {
get: function() { get: function() {
var err = new Error(this.message); if (cause) {
err.name = this.name; cause.name = "" + ex.name;
try { stack = "" + cause.stack;
throw err; var msg = "" + cause.message;
} catch (e) { cause = null;
return e.stack; 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) { function DefaultsError(msg, defs) {
this.message = msg; this.message = msg;
this.defs = defs; this.defs = defs;
configure_error_stack(this, new Error(msg));
} }
DefaultsError.prototype = Object.create(Error.prototype); DefaultsError.prototype = Object.create(Error.prototype);
DefaultsError.prototype.constructor = DefaultsError; DefaultsError.prototype.constructor = DefaultsError;
DefaultsError.prototype.name = "DefaultsError"; DefaultsError.prototype.name = "DefaultsError";
configure_error_stack(DefaultsError);
function defaults(args, defs, croak) { function defaults(args, defs, croak) {
if (croak) for (var i in args) { if (croak) for (var i in args) {