Last active
January 16, 2019 22:12
-
-
Save Marsup/3a0e3ed2520a5d1afd37 to your computer and use it in GitHub Desktop.
Custom error with cross browser support
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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