Learning web development: JavaScript exceptions
Briefly

JavaScript classes act like factories that are invoked with new and always return objects called instances. The instanceof operator checks whether a value is an instance of a given class. Built-in classes like Array and Object have literal equivalents that are usually preferred because the constructor forms have quirks. The Error class represents runtime errors and exposes properties such as error.stack, which records where an Error instance was created in source code. Reading stack traces makes it possible to pinpoint where errors occurred. A sample project shows Node.js output with error messages and stack lines including file and line numbers.
A class in JavaScript is similar to a function: We invoke it with arguments and it returns a result. Two things are different: A class is invoked via new plus the typical function call syntax. The reason for that is historical. A class always returns objects. It is a factory for objects. These objects are called the instances of that class.
In this section, we look at two built-in classes. We can also define our own classes but that is beyond the scope of this series. Roughly, the following two expressions are equivalent: However, the former has a few quirks, which is why the array literal is virtually always the better choice. Similarly, new Object() is equivalent to {}.
Property error.stack tells us where in the source code an Error instance was created. That means we can tell where an error happened! Project create-error.js demonstrates how that works: Running it via Node.js produces the following output (there are more lines, but those are not interesting): Error: Something went wrong! at createError (create-error.js:2:10) at Object.<anonymous> (create-error.js:5:13) err was created in line 2 column 1
Read at 2ality
[
|
]