Skip to content

Instantly share code, notes, and snippets.

@Marsup
Last active January 16, 2019 22:12
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Marsup/3a0e3ed2520a5d1afd37 to your computer and use it in GitHub Desktop.
Save Marsup/3a0e3ed2520a5d1afd37 to your computer and use it in GitHub Desktop.
Custom error with cross browser support
const CustomError = function CustomError() {
if (Error.captureStackTrace) { // Chrome
Error.captureStackTrace(this, CustomError);
} else {
const err = new Error();
let processedStack, fileName, lineNumber;
Object.defineProperties(this, {
stack: {
get: function() {
if (processedStack) {
return processedStack;
}
const stack = err.stack;
if (!stack) { // IE...
return;
}
processedStack = stack.substr(stack.indexOf('\n') + 1);
return processedStack;
}
},
fileName: {
get: function() {
if (fileName) {
return fileName;
}
const stack = this.stack;
if (!stack) { // IE...
return;
}
const det = /^(.*?)@(.*?):(.*?)$/.exec(stack.split('\n')[1]);
fileName = det[2];
lineNumber = det[3];
return fileName;
}
},
lineNumber: {
get: function() {
if (lineNumber) {
return lineNumber;
}
const stack = this.stack;
if (!stack) { // IE...
return;
}
const det = /^(.*?)@(.*?):(.*?)$/.exec(stack.split('\n')[1]);
fileName = det[2];
lineNumber = det[3];
return lineNumber;
}
}
});
}
}
CustomError.prototype = Object.create(Error.prototype);
CustomError.prototype.constructor = CustomError;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment