I’m attempting to create custom error objects in Node that use Error as the prototype and then to return these errors to the client via the express res.json()
method. I can create an instance of a custom error, set it’s properties but when I call res.json()
, the stack property is missing. I believe this is due to JSON.stringify()
not following prototypes?
I can’t see a way of creating custom error objects with an arbitrary number of properties and then use JSON.stringify()
on these objects to return all the properties and the base class / superclass Error
stack property. Please help! An example is below:
(function (customErrorController) {
function CustomError() {
this.name = 'CustomError'; // String
this.message = null; // String
this.errorCode = null; // String
// this.stack exists as CustomError inherits from Error
}
CustomError.prototype = new Error();
customErrorController.init = function (app) {
app.get('/test', function (req, res) {
var customError = new CustomError();
customError.message = 'The Message';
customError.errorCode = 'Err001';
console.log(customError.stack); // This logs the stack fine
res.json(customError); // The stack is missing when outputting the object as JSON
});
};
})(module.exports);