Skip to content

Instantly share code, notes, and snippets.

@webbower
Created November 9, 2019 02:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save webbower/141893ca2a9a5c3997970e7818cbfebf to your computer and use it in GitHub Desktop.
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
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