Better polyfill for Error.captureStackTrace in Meteor.makeErrorType.

The trick of returning an object other than `this` from the constructor
function makes the classes created by Meteor.makeErrorType impossible to
subclass, unless the subclass is very careful to return the same object
from its own constructor.

Fortunately, the only reason we needed an actual Error instance in this
code was to get access to its .stack property, which we can just as easily
borrow from an auxiliary Error object.
This commit is contained in:
Ben Newman
2016-01-19 14:57:53 -05:00
parent 0907f52f53
commit f0a84785db

View File

@@ -4,26 +4,19 @@
//
Meteor.makeErrorType = function (name, constructor) {
var errorClass = function (/*arguments*/) {
var self = this;
// Ensure we get a proper stack trace in most Javascript environments
if (Error.captureStackTrace) {
// V8 environments (Chrome and Node.js)
Error.captureStackTrace(self, errorClass);
Error.captureStackTrace(this, errorClass);
} else {
// Firefox
var e = new Error;
e.__proto__ = errorClass.prototype;
if (e instanceof errorClass)
self = e;
// Borrow the .stack property of a native Error object.
this.stack = new Error().stack;
}
// Safari magically works.
constructor.apply(self, arguments);
constructor.apply(this, arguments);
self.errorType = name;
return self;
this.errorType = name;
};
Meteor._inherits(errorClass, Error);