Prepare an Error for JSON serialization
MIT License
Serializes any input (preferrably an Error) to a plain old JavaScript Object which has the following guarantees:
The error will be exposed if:
NODE_ENV
is "development"
, or;expose
option is true
, or;expose
property is true
, or;status
property contains a number less than 500
.Has at least a name
property and a message
property, both always Strings.
They default to "Error"
and "Something went wrong"
Other enumerable properties are copied under the following conditions:
JSON.stringify
(unless unsafe
).const serializeHttpError = require('serialize-http-error');
const app = require('express')();
app.use((err, req, res, next) => {
res.status(err.status || 500);
res.json(serializeHttpError(err));
});
The second argument to serializeHttpError
may be an object with options, eg:
serializeHttpError(err, {
unsafe: true,
flat: true,
expose: false
});
unsafe
false
If set to true
, all enumerable properties, even recursive ones, will be
copied. This allows for customized resolution of these properties, for example
by using the replacer
argument in JSON.stringify
.
flat
false
By default, nested Error objects are also serialized. If set to true
, they
will be left intact.
expose
process.env.NODE_ENV === 'development'
If set to true
, all errors will be exposed. If set to false, only exposable
errors are exposed.
defaultName
'Error'
The default name to use for values which don't have a name, or errors which may not be exposed.
defaultMessage
'Something went wrong'
The default message to use for values which don't have a message, or errors which may not be exposed.