I am trying to copy an err object to error as shown here let error = { ...err };
the err object has a name property but when I console log the name property of cloned object I get undefined! When I console log the whole cloned object I get [object Object]! what could be wrong!
This is happening in NODE JS
and this is the code and the console log
if (process.env.NODE_ENV === 'development') {
// eslint-disable-next-line no-console
console.log('from DEV_<<<< ERROR >>>>');
throwDevError(err, res);
} else if (process.env.NODE_ENV === 'production') {
//PROBLEM OCCURING HERE
let error = { ...err };
// eslint-disable-next-line no-console
//CONSOLE LOGGING OCCURING HERE
console.log(`PROD_<<<< ERROR >>>>, ${error} ${process.env.NODE_ENV}`);
if (error.name === 'CastError') error = mongoDBCastError(error);
throwProdError(error, res);
if (error.name === 'ValidationError') error = mongoDBValidationError(error);
throwProdError(error, res);
}
next();
};
//RESULTS OCCURING HERE (Im creating the error using express after making an api call using postman) and here is the console log result I get
Hi, [Object Object] appears because it is included in a string, I don’t know how to help you, but if you don’t include the object inside a string, console.log () shows it fine:
let myObj = { name:"Juan" }
console.log(myObj)
{nombre: 'Juan'}
EDITED
Already achieved! You must use JSON.stringify (). This will turn your object into a string and you can display it on the screen.
let myObj = { name:"Juan" }
console.log("Hi, my object is "+JSON.stringify(myObj))
@juangpereira I have realized I have not explained the problem correctly. The problem is the object I have ‘spread’ into the new error object does not have the ‘contents’ of the original object. The original is err and is from express and wanted to shallow copy using spread. However when i try accessing error.name i get undefined but err has err.name
PROD_<<<< ERROR >>>> production undefined PROD_<<<< ERROR >>>> ValidationError
yet error is a copy or err. what could be wrong, please. I just don’t want to manipulate the original err object
Not sure I see the point in making a copy if you are just going to reassign the error variable with a new value. Are the functions mutating the object and if so why not make them non-mutating instead? If they are not, why do you need a copy?
Where is the err object coming from exactly?
It might help if you have a live example we can look at. Or at least a repo with the full code.
Anyway, [object Object] usually means the object has somehow has been turned into a string.
Ok, so I can’t help you, later if nobody solved the error I’ll keep trying. But do not focus on how you copy the object because the problem is not that. If you copy an object, you will be able to access the properties from the copy. The problem should be elsewhere.
let myObj = { name:'Juan' }
let myClonObj = {...myObj}
console.log('Property name: '+myClonObj.name)
Okey thank you., but I’m wondering why the copied object does not copy as expected especially the name property while it copies other properties. I’m sure I will need to copy with same method sometimes in my development journey and that may not be good. I just want to understand why it behaved that way
It is difficult to know because I cannot do the tests because you are the one who has the code to execute it. Many times the errors are not where we expect them and to discover them you have to try anything that comes to mind. Don’t just stare at the line where you copy the object, look at the object, see how you did it, see how you defined the variable ‘error’, maybe changing let to var or const the result is different. This type of test can only be done by you.
I mean, those are kinds of tests that I would do, but someone with more knowledge than me I suppose would find the error without doing all of that.
You can’t do what you’re trying to do because there is no property called “message” on the Error object, it’s attached to the prototype. Same reason that you won’t get the toString function by copying via destructuring the object: it literally isn’t there, it’s on a seperate object. Look:
const example = { aProperty: 1 }
const { toString, isPrototypeOf, hasOwnProperty, aProperty } = example;
console.log(aProperty) // 1, property of object
console.log(toString) // undefined, not property of object, is on prototype
console.log(isPrototypeOf) // undefined, not property of object, is on prototype
console.log(hasOwnProperty) // undefined, not property of object, is on prototype
@lasjorg@juangpereira Here is a repo in GitHub I have created for the same right now https://github.com/imehappen/LearnSomeNojeJS. The Error class and handler are in utilities\globalErrorHandler.js
in the globalErrorHandler.js there’s a comment //PROBLEM OCCURS HERE please feel free to ask any question related to the uploaded codes
@DanCouper I wanted to create my own error by manipulating the js native error so that I can use it for sending well-structured responses to the requests made. I have looked at the err object (the one I want to copy ie err) and it has all I need for the properties but the copied obj doesn’t have all the properties I need, there is a link above with the codes now.
Right. I have only glanced at the code but it seems like a standard custom error: there may be some issue with it, I haven’t ran it. But if you do this:
const { ...myErr } = someErrorObiect
That just copies the properties. So if you have an error object (and as yours extends an error object, it’s an error object), you don’t get prototype properties. And message is on the prototype. Error objects. for various reasons, are not just like
{ message: "some error message" }
They are just designed to look like that in terms of access, so you can get the message via someErrorObject.message, but message gets and sets an internal slot on that error instance
I don’t really understand why you’re trying to copy the error object, but a shallow copy of an instance of Error will not give you very much. That’s not how you use errors
Hello, this has troubled me till now! I have not been able to copy that err to error using {...err} syntax and its giving me no sleep at all! I dont understand why!!
For the third time, you are trying to copy properties which are on the prototype. Spread does not copy prototype properties. You are just making a copy of the properties that are directly defined on the instance of that error object. The properties you seem to want do not exist on that shallow copy.
I still do not understand why you are trying to copy it in the first place.