Created
February 18, 2020 11:57
-
-
Save eyecatchup/0686aa8a81a537675b4de8ed592d0227 to your computer and use it in GitHub Desktop.
Custom replace function for JSON.stringify to stringify JS Error Objects.
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
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