Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@eyecatchup
Created February 18, 2020 11:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eyecatchup/0686aa8a81a537675b4de8ed592d0227 to your computer and use it in GitHub Desktop.
Save eyecatchup/0686aa8a81a537675b4de8ed592d0227 to your computer and use it in GitHub Desktop.
Custom replace function for JSON.stringify to stringify JS Error Objects.
jsonFriendlyErrorReplacer = (key, value) => {
if (value instanceof Error) {
value = Object.assign({},
value, // Pull all enumerable properties, supporting properties on custom Errors
{ // Explicitly pull Error's non-enumerable properties
name: value.name,
message: value.message,
stack: value.stack
}
)
}
return value
}
let obj = {
error: new Error('nested error message')
}
console.log('Result WITHOUT custom replacer:', JSON.stringify(obj))
console.log('Result WITH custom replacer:', JSON.stringify(obj, jsonFriendlyErrorReplacer, 2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment