if I console.log an object, it outputs all the key/value pairs as well as its methods.
const obj = {
name: "Mike",
add : function (a, b){
return a + b
}
}
console.log(obj)
but the error object in try…catch block, console.log(err)
outputs message something like "reference error: variable is not defined"
try {
variable
}
catch(err) {
console.log(err)
}
Why does it outputs message, instead of its key/value pairs and methods?
2
Answers
The underlying conversion of arguments into console messages for
console.log()
does not have to always print out the key-value pairs of object and varies from environment to environment.For example, the
console
object in NodeJS usesutil.format()
to perform the conversion, and that in turn callsutil.inspect()
to format object, which treatsError
objects differently to normal objects. I’m not sure about the specifics for other browsers, however, but they probably also treatError
objects differently as well to aid debugging.Does this answer your question?
When catching an error using a
try...catch
block, you’re dealing with an instance of one the error objects (name, message, stack*). The error object is created with the specific error information, including thename
andmessage
properties, and possibly thestack
property.The
err
object is an instance ofReferenceError
, and it contains a message property that describes the error message, which isReferenceError: variable is not defined.
This is what gets logged when you callconsole.log(err)
.If you want to access other properties and methods of error objects, you can do so explicitly. For example, you can log the name and stack properties like this: