Best practices for logging error objects in JavaScript

As a beginner in web development, I've recently come across an interesting observation related to handling errors. When working with json.stringyfy(), I noticed that the message key is not displayed in statement 2. However, accessing error.message returns a value instead of undefined.

 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" }

While developing an express application and encountering this error from Mongoose, I believe this behavior is prevalent across JavaScript.

statement 4 logs

[ 'index', 'code', 'keyPattern', 'keyValue' ]

Answer №1

"message" is not considered a key (refer to statement 4)

Although technically it is, Object.keys is specifically designed to display only enumerable properties, and message happens to be non-enumerable.

According to the ECMAScript specification, the Error constructor sets its message (and other properties) through the process described as:

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

Additional custom properties can be added to Error objects using JavaScript code, which clarifies why other properties do appear when using Object.keys().

Regarding the output of console.log: the way objects are displayed can vary significantly based on the console API implementation.

To display those non-enumerable properties as well, you can utilize:

console.log(Object.getOwnPropertyNames(error))

Answer №2

Like @trincot mentioned, the reason why message is not displayed is because it is a non-enumerable attribute for Error constructor. The MongoServerError overrides the MongoError, which in turn overrides the JS Error object. If you want to know the attributes of the error, you can refer to the provided links.

If you need to access all attributes, including the non-enumerable ones, you can use Object.getOwnProperties(error) to view them.

Alternatively, you can utilize Object.getOwnPropertyDescriptors(error) to understand the descriptor for each attribute defined in the object.

Answer №3

Unfortunately, the error stack and message fields cannot be enumerated. Here is a helpful function that can extract all properties from an error object, including any custom fields you may have added:

const err = new Error('An unexpected error occurred.');
err.details = { custom: { code: '123' } };

console.log(errorToPOJO(err)); // {"stack":"Error: An unexpected error occurred.\\n    at <anonymous>:1:13","message":"An unexpected error occurred.","details":{"custom":{"code":"123"}}

function errorToPOJO(error) {
  const ret = {};
  for (const propertyName of Object.getOwnPropertyNames(error)) {
    ret[propertyName] = error[propertyName];
  }
  return ret;
};

Answer №4

For those utilizing an API, give this a shot

console.log(error.message.toString())

Answer №5

Expanding on the previous answer, you can obtain the enumerable properties by running the following code:

console.log(JSON.stringify(error, Object.getOwnPropertyNames(error)))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A guide on implementing multiline properties in a property file for Selenium WebDriver

At the moment, I am focusing on utilizing Selenium WebDriver with code that is developed in Java. In the snippet below, I have successfully verified if the dropdown values match the UI for one dropdown. Now, I aim to extend this capability to check multip ...

Undefined Children Component

I am currently working on creating Auth routes and I am facing an issue where the children are undefined, resulting in a blank page. In my App.js file, I have implemented a PrivateRoute component as shown below. Interestingly, when I replace PrivateRoute w ...

What are the best ways to store internal files in node.js for faster access?

I have been utilizing routing functions like the one mentioned below to replicate the overall design of my website (A.jade): exports.overview = function(req, res, next) { res.render('A', { main: jade.renderFile('./views/B.jade' ...

I'm trying to establish a connection to MongoDB within the getStaticProps function in Next.js. Can anyone

Hello, I am a beginner in next.js and I have successfully rendered the home page on the server by populating the props object through a file named "products.json". Now, my next goal is to populate the props object in the function called getStaticProps usin ...

"Enhanced jQuery confirmation dialog plugin with full screen functionality and automatic

My current web-based production tracking system isn't getting the attention it needs from users, so I'm in the process of creating a full-screen alert and confirm function to ensure they pay closer attention. The idea is for alerts to remain on t ...

Having issue with jQuery popup not functioning correctly on the right side with the contact form. Is there anyone who knows how

Looking for a side slide popup that only accepts paragraph content? Want to add a contact form to it? Check out this fiddle - link here For a working example, visit - $(function() { // Slide from right to left $('#test2').PopupLayer({ ...

Using JavaScript, include a child class into a parent class

I am facing an issue with my class hierarchy, which includes classes like Parent, Child1 (which extends Parent), and Child2. Parent contains an array of child items, but importing Child1 and Child2 into Parent leads to circular dependencies and errors whe ...

What is the best way to iterate through files within a directory and its nested subdirectories using electron?

I am currently working on developing a desktop application that involves scanning through a directory, including all subdirectories, to locate files containing specific characters in their filenames. Is it feasible to accomplish this task using Electron? ...

Can you provide a tutorial on creating a unique animation using jQuery and intervals to adjust background position?

I am attempting to create a simple animation by shifting the background position (frames) of the image which serves as the background for my div. Utilizing Jquery, I aim to animate this effect. The background image consists of 6 frames, with the first fr ...

React-redux: There is a TypeError in the code, as _this2.props.handleCityChange is not recognized as

I am currently working on integrating a weather widget in react-redux. I keep encountering the error message "TypeError: _this2.props.handleCityChange is not a function" and similar errors for other functions as well. Despite referring to the redux documen ...

Issue with jQuery: submit() function not behaving as expected when navigating back in history

Incorporating jQuery's submit() method in order to perform basic form verification prior to redirecting the user to the subsequent page. $(document).ready(function(){ $("form").submit(function() { // carry out form validation and set erro ...

What is causing this code to display an error message?

An issue has been identified in the second line. "ReferenceError: specialTrick is not defined at CoolGuy.showoff (<anonymous>:23:40) at <anonymous>:31:5 at Object.InjectedScript._evaluateOn (<anonymous>:875:140) at Object ...

Is there a way to modify the appearance of blocks in Scratch/Blockly?

I am currently working on customizing the appearance of the blocks in Scratch by looking into adjusting the GitHub repository of scratch-blocks (https://github.com/LLK/scratch-blocks). There is a chance that I might need to modify the GitHub repository of ...

Sending a collection of text inputs from a web form and saving them in MongoDB

I have been attempting to store an array of strings from my HTML form into my database (MongoDB). Here's the HTML form for creating a new class: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"& ...

Attempting to decode JSON data

I'm new to node.js and trying to learn how to send a JSON object using REST. However, I keep getting an error message that says "SyntaxError: Unexpected token  in JSON at position 0". I've checked the JSON using an online validator and it seem ...

Is it possible to use an Ajax callback function to add a select dropdown HTML to a table

I am currently in the process of using jQuery to append some HTML with the code provided below. My main objective is to select an option based on AJAX response data and create a select dropdown menu. However, the variable scope of sOut doesn't seem to ...

Handling scroll events in a functional component using React

I'm having trouble understanding why the onScroll function isn't triggering the console.log statement. <table className="table" onScroll={()=>{console.log("Works")}> The console.log just doesn't seem to be exec ...

Switching over the database for a session away from using ajax

I am currently working with an XML API that interacts with a database. My website utilizes the functions of this XML API to retrieve data from the database. I am facing a challenge where I need to update the database based on the user's selection on t ...

Deactivate the collapse toggle feature in the footer navigation

I've recently started using bootstrap and I'm having some trouble adding a social nav footer to my portfolio. I've experimented with removing different classes and even tried using the sticky footer feature, but it's not quite what I ne ...

Struggling with incorporating a search feature? Encounter the error message "TypeError: data.filter is not a function"?

UPDATE: here is what console.log(data) shows. The data appears correctly, but the filtering process seems to be malfunctioning.] !https://imgur.com/a/SsEDAKj! UPDATE 2: this.state.items represents an array. I am currently working on integrating a search ...