errors
errors copied to clipboard
Restify next(err) don't serialize extraneous options created by makeConstructor
When sending error with next(error) callback, response sent to client does not contain optionnal properties of my new Error Object created with makeConstructor restify-errors module.
Env : Node v12.18.3 with ESM loader (type: "module") in package.json
Example :
import errs from 'restify-errors';
const TestError = errs.makeConstructor("TestError", {
statusCode: 500,
info: {errcode: "ERR_GENERIC"},
message:"App Error"
});
const tmp = new TestError();
console.log("tmp.info exists : ", JSON.stringify(tmp.info));
console.log("But this is sent to client when next(tmp) called : ", JSON.stringify(tmp));
Print :
tmp.info exists : {"errcode":"ERR_GENERIC"}
But this is sent to client when next(tmp) called : {"code":"Test","message":"App Error"}
It seems to be caused by JSON.stringify that only check for ownProperties (it don't look for prototype chain).
I finally used this workaround :
import errs from 'restify-errors';
const toJSONf= function() {
let tmp = {};
for(let key in this) {
if(typeof this[key] !== 'function' && !key.startsWith('jse_') && key!=="body")
tmp[key] = this[key];
}
return tmp;
}
const TestError = errs.makeConstructor("TestError", {
statusCode: 500,
info: {errcode: "ERR_GENERIC"},
message:"App Error",
toJSON: toJSONf
});