What to throw? Error or bare string dilemma

How Errors are inferior and superior to bare strings

Marian C.
Geek Culture

--

What is Error?

It is an ordinary class. The modern constructor of Error has two parameters, both are optional:

new Error(message, options)

Just creating a new Error object has no special effect. To interrupt code execution and see an error message in the console, the Error has be thrown with a throw statement.

To explore the properties of Errors, let’s execute a sample code throwing an Error:

// 1.js
const err = new Error('MyMessage', { cause: new RangeError("chainedMessage") });
err.name = 'MyError';
console.dir(err);
throw err;

If you visit the sample page you can see the output in the console:

Errors always have at least 3 properties:

  • name — in built-in subclasses of Error it is the name of the class. name can be changed in an Error object, but cannot be set in the constructor.
  • message — a string passed as the first argument to the constructor

--

--

Marian C.
Geek Culture

Java, JavaScript and SQL developer. Interested in data collection and visualization.