Search code examples
javascripttry-catch

Why console.log(error_object) outputs an error message and not its key/value pairs and methods?


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?


Solution

  • 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 the name and message properties, and possibly the stack property.

    The err object is an instance of ReferenceError, and it contains a message property that describes the error message, which is ReferenceError: variable is not defined. This is what gets logged when you call console.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:

    console.log(err.name);
    console.log(err.stack);