Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

179
Vistas
How to properly log error object in javascript

I am a fairly new to web development and have not given much thought to error. But today I noticed something I have to use json.stringyfy() to see the entire error object. Also message key is not shown in statement 2 but when I print error.message I get a message instead of undefined. "message" is not even a key(check statement 4) but still logging error.message logs a value(typeof(error.message) is string) .

 try {
           //Some error occours
    } catch (error) {
        console.log(JSON.stringify(error)) //statement 1
        console.error(error) //statement 2
        console.log(error.message) //statement 3
        console.log(Object.keys(error)) //statement 4
    }

statement 1 logs

MongoServerError: E11000 duplicate key error collection: trendyApp.Markets index: name_1 dup key: { name: "murat market" }
    at D:\web projects\trendyApp\server\node_modules\mongodb\lib\operations\insert.js:51:33
    at D:\web projects\trendyApp\server\node_modules\mongodb\lib\cmap\connection_pool.js:273:25
    at handleOperationResult (D:\web projects\trendyApp\server\node_modules\mongodb\lib\sdam\server.js:363:9)
    at MessageStream.messageHandler (D:\web projects\trendyApp\server\node_modules\mongodb\lib\cmap\connection.js:474:9)
    at MessageStream.emit (events.js:375:28)
    at processIncomingData (D:\web projects\trendyApp\server\node_modules\mongodb\lib\cmap\message_stream.js:108:16)
    at MessageStream._write (D:\web projects\trendyApp\server\node_modules\mongodb\lib\cmap\message_stream.js:28:9)
    at writeOrBuffer (internal/streams/writable.js:358:12)
    at MessageStream.Writable.write (internal/streams/writable.js:303:10)
    at TLSSocket.ondata (internal/streams/readable.js:726:22) {
  index: 0,
  code: 11000,
  keyPattern: { name: 1 },
  keyValue: { name: 'murat market' }
}

statement 2 logs

{"index":0,"code":11000,"keyPattern":{"name":1},"keyValue":{"name":"murat market"}}

statement 3 logs

E11000 duplicate key error collection: trendyApp.Markets index: name_1 dup key: { name: "murat market" }

I saw this behavior while I was making an express application and the error is generated by mongoose but I think this would be common throughout javascript

statement 4 logs

[ 'index', 'code', 'keyPattern', 'keyValue' ]
over 4 years ago · Santiago Trujillo
4 Respuestas
Responde la pregunta

0

"message" is not even a key(check statement 4)

It is, but Object.keys is designed to list enumerable properties, and message is not enumerable.

In the ECMAScript specification, we see in the section on the Error constructor that the constructor creates its message (and other properties) with the procedure:

Perform CreateNonEnumerableDataPropertyOrThrow(O, "message", msg).

Other -- custom -- properties can of course be added to Error objects by JavaScript code, which explains why other properties are listed by Object.keys().

As to the output of console.log: the console API implementation has a lot of freedom on how to display objects -- lot's of differences can be found between implementations.

To also output those non-enumerable properties, use

console.log(Object.getOwnPropertyNames(error))
over 4 years ago · Santiago Trujillo Denunciar

0

As @trincot said, it is not shown because of message is a non enumerable attribute for Error constructor, the MongoServerError is overriding the MongoError and actually this is overriding the JS Error object, so if you need to know what attributes you have into the error you can check the previous links to see what attributes you can check.

Also if you want to get all the attributes (included the non enumerable ones) you can use Object.getOwnProperties(error) to see all the attributes that the given object has.

Also you can use Object.getOwnPropertyDescriptors(error) to know what is the descriptor for each attribute you've defined into the given object.

over 4 years ago · Santiago Trujillo Denunciar

0

Sadly error stack and message fields are not enumerable, below is a utility function that extracts all properties from an error object, even custom fields you assign to errors:

const err = new Error('Something bad happened.');
err.metadata = { custom: { field: '1' } };


console.log(errorToPOJO(err)); // {"stack":"Error: Something bad happened.\\n    at <anonymous>:1:13","message":"Something bad happened.","metadata":{"custom":{"field":"1"}}

function errorToPOJO(error) {
  const ret = {};
  for (const properyName of Object.getOwnPropertyNames(error)) {
    ret[properyName] = error[properyName];
  }
  return ret;
};
over 4 years ago · Santiago Trujillo Denunciar

0

Try this if your using api

console.log(error.message.toString())
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda