Skip to content

Commit 59e3855

Browse files
authored
improve interoperability of custom Errors (#5752)
closes #5751
1 parent 574ca47 commit 59e3855

File tree

2 files changed

+17
-13
lines changed

2 files changed

+17
-13
lines changed

lib/parse.js

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -207,11 +207,10 @@ function JS_Parse_Error(message, filename, line, col, pos) {
207207
this.line = line;
208208
this.col = col;
209209
this.pos = pos;
210+
configure_error_stack(this, new SyntaxError(message, filename, line, col));
210211
}
211-
JS_Parse_Error.prototype = Object.create(Error.prototype);
212+
JS_Parse_Error.prototype = Object.create(SyntaxError.prototype);
212213
JS_Parse_Error.prototype.constructor = JS_Parse_Error;
213-
JS_Parse_Error.prototype.name = "SyntaxError";
214-
configure_error_stack(JS_Parse_Error);
215214

216215
function js_error(message, filename, line, col, pos) {
217216
throw new JS_Parse_Error(message, filename, line, col, pos);

lib/utils.js

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -55,28 +55,33 @@ function find_if(func, array) {
5555
for (var i = array.length; --i >= 0;) if (func(array[i])) return array[i];
5656
}
5757

58-
function configure_error_stack(fn) {
59-
Object.defineProperty(fn.prototype, "stack", {
58+
function configure_error_stack(ex, cause) {
59+
var stack = ex.name + ": " + ex.message;
60+
Object.defineProperty(ex, "stack", {
6061
get: function() {
61-
var err = new Error(this.message);
62-
err.name = this.name;
63-
try {
64-
throw err;
65-
} catch (e) {
66-
return e.stack;
62+
if (cause) {
63+
cause.name = "" + ex.name;
64+
stack = "" + cause.stack;
65+
var msg = "" + cause.message;
66+
cause = null;
67+
var index = stack.indexOf(msg);
68+
if (index >= 0) index += msg.length;
69+
index = stack.indexOf("\n", index) + 1;
70+
stack = stack.slice(0, index) + stack.slice(stack.indexOf("\n", index) + 1);
6771
}
68-
}
72+
return stack;
73+
},
6974
});
7075
}
7176

7277
function DefaultsError(msg, defs) {
7378
this.message = msg;
7479
this.defs = defs;
80+
configure_error_stack(this, new Error(msg));
7581
}
7682
DefaultsError.prototype = Object.create(Error.prototype);
7783
DefaultsError.prototype.constructor = DefaultsError;
7884
DefaultsError.prototype.name = "DefaultsError";
79-
configure_error_stack(DefaultsError);
8085

8186
function defaults(args, defs, croak) {
8287
if (croak) for (var i in args) {

0 commit comments

Comments
 (0)