What to throw? Error or bare string dilemma
How Errors are inferior and superior to bare strings
Published in
4 min readNov 28, 2021
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 Error
s, 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:
Error
s always have at least 3 properties:
name
— in built-in subclasses ofError
it is the name of the class.name
can be changed in anError
object, but cannot be set in the constructor.message
— a string passed as the first argument to the constructor