i'm creating a custom express middleware to handle errors thrown by mongoose.
the error
has a message
property:
//works as intended
console.log(error.message); //E11000 duplicate key error collection
but when i want to send the entire object, the message
property doesn't show up:
res.status(400).json(error);
/*
recieved response:
{
"index": 0,
"code": 11000,
"keyPattern": {
"name": 1
},
"keyValue": {
"name": "Some Name"
}
}
*/
destructuring doesn't work either:
res.status(400).json({ ...error });
//same response as before
it doesn't show it in Object.keys() either:
console.log(Object.keys(error)); //[ 'index', 'code', 'keyPattern', 'keyValue' ]
but this statement is true:
console.log("message" in error); //true
i don't know why it behaves this way but what is the workaround ?
CodePudding user response:
Seems like the message
property on error
object is non-enumerable
. If a property is non-enumerable
, it cannot be serialised (res.json
serialises the input JSON), won't appear in Object.keys
or get destructured
.
Your best bet is either to explicitly set the enumerable
as true
on error.message
, or copy the error.message
on some other key inside error
object.
// For initialisation
Object.defineProperty(error, 'message', {enumerable: true, value: ''});
//OR
const errorMessage = error.message;
error.customMessage = errorMessage;
// Now use error.customMessage instead of error.message
// OR
// Create a new object with the above retrieved error.message
const customError = {...error, message: customMessage};
// use customError object now
res.status(400).json(customError);
More details : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty
CodePudding user response:
you should use :
let message = `${Object.values(error.keyValue)} is duplicated/already exists, please choose another one`
console.log(message) // name is duplicated/already exists, please choose another one