Created
November 9, 2019 02:06
-
-
Save webbower/141893ca2a9a5c3997970e7818cbfebf to your computer and use it in GitHub Desktop.
Extract data from error objects for serialization since Error instances are weirdly finicky and not straightforward to pull data from
This file contains 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 builtInErrorTypes = [ | |
Error, | |
EvalError, | |
RangeError, | |
ReferenceError, | |
SyntaxError, | |
TypeError, | |
URIError, | |
]; | |
// ES5 | |
function extractErrorData(errorInstance) { | |
// Extract standard fields | |
const errorData = ['name', 'message', 'stack'].reduce(function(err, field) { | |
err[field] = errorInstance[field]; | |
return err; | |
}, {}); | |
// Copy line and column numbers if present | |
errorData.lineNumber = errorInstance.lineNumber || errorInstance.line || undefined; | |
errorData.columnNumber = errorInstance.columnNumber || errorInstance.column || undefined; | |
// Extract additional fields of custom Error subclasses | |
if (builtInErrorTypes.every(function(errorType) { return Object.getPrototypeOf(errorInstance).constructor !== errorType; })) { | |
Object.getOwnPropertyNames(errorInstance).forEach(function(field) { | |
if (!(field in errorData)) { | |
errorData[field] = errorInstance[field]; | |
} | |
}); | |
} | |
return errorData; | |
} | |
// ES6 | |
const extractErrorData = errorInstance => { | |
// Extract standard fields | |
const errorData = ['name', 'message', 'stack'].reduce((err, field) => { | |
err[field] = errorInstance[field]; | |
return err; | |
}, {}); | |
// Copy line and column numbers if present | |
errorData.lineNumber = errorInstance.lineNumber || errorInstance.line || undefined; | |
errorData.columnNumber = errorInstance.columnNumber || errorInstance.column || undefined; | |
// Extract additioinal fields of custom Error subclasses | |
if (builtInErrorTypes.every(errorType => Object.getPrototypeOf(errorInstance).constructor !== errorType)) { | |
Object.getOwnPropertyNames(errorInstance).forEach(field => { | |
errorData[field] = errorInstance[field]; | |
}) | |
} | |
return errorData; | |
} | |
console.log(extractErrorData(new RangeError('foo'))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment