Home Blog CV Projects Patterns Notes Book Colophon Search

JSON Stringify Error Object

8 Feb, 2017

By default JSON.stringify gives an empty object for errors on node stable:

const error = new Error('Show this error please')
JSON.stringify({error: error})

Gives:

'{"error":{}}'

But here's how you can encode it:

function replaceError(key, value) {
  if (value instanceof Error) {
    const error = {};
    Object.getOwnPropertyNames(value).forEach((key) => {
      error[key] = value[key];
    });
    return error;
  }
  return value;
}

function replaceErrorMessageOnly(key, value) {
  if (value instanceof Error) {
    return {message: value.message}
  }
  return value;
}

Thanks: http://stackoverflow.com/questions/18391212/is-it-not-possible-to-stringify-an-error-using-json-stringify

Copyright James Gardner 1996-2020 All Rights Reserved. Admin.