The Error Object

In JavaScript, exceptions and failures are represented by standard Objects, appropriately named Error.

The most important property on the built-in Error object is the .message property, which contains a human-readable description of what went wrong.

Creating an Error

You can instantiate a new Error object at any time using the new keyword, passing the descriptive message into the constructor.

const err = new Error("We've run out of baked salmon");

console.log(err.message);
// Output: We've run out of baked salmon

Wrapping Errors

Sometimes, it is useful to create a factory function that standardizes how error messages are formatted across an entire application.

// A simple factory function to standardize error formatting
function createFormattedError(message) {
  return new Error(`[System Failure]: ${message}`);
}

const err = createFormattedError("Database connection lost");

console.log(err.message);
// Output: [System Failure]: Database connection lost

Note: Simply creating an Error object does not actually stop the program. To do that, the error must be “thrown”, which we will cover in an upcoming lesson.