How to print a message in error handling with try-catch with JavaScript?

Sometimes, we want to print a message in error handling with try-catch with JavaScript.

In this article, we’ll look at how to print a message in error handling with try-catch with JavaScript.

How to print a message in error handling with try-catch with JavaScript?

To print a message in error handling with try-catch with JavaScript, we can log the stack, name and message properties.

For instance, we write:

const x = {
  asd: "asd",
};

try {
  JSON.parse(x);
} catch (e) {
  console.log("Error", e.stack);
  console.log("Error", e.name);
  console.log("Error", e.message);
}

The stack property has the stack trace string.

name has the error name as a string.

And message has the error message as a string.

Therefore, we should see 'Error SyntaxError' and 'Error Unexpected token o in JSON at position 1' logged respectively for e.name and e.message.

Conclusion

To print a message in error handling with try-catch with JavaScript, we can log the stack, name and message properties.