Sub topic 1
What an Error Object Contains
Prerequisites
This chapter assumes you know JavaScript functions, ES2015 class syntax with extends and super, and throw with try/catch. You should also be able to run code in Node.js or a browser console.
The Three Standard Properties
Every Error has these three properties:
messageis the human-readable text you pass to the constructor. It is an own property of the error.nameidentifies the kind of error. Plain errors inherit'Error'fromError.prototype.stackis a string that lists the call frames active when the error was created. No specification defines it, but every major engine supports it.
String(err) combines the first two as name: message.
The Built-in Error Types
JavaScript throws several subclasses of Error itself:
| Type | Typical trigger |
|---|---|
| `TypeError` | Calling a non-function, or reading a property of `undefined` |
| `RangeError` | A value is outside its allowed range, as in `new Array(-1)` |
| `SyntaxError` | `JSON.parse` receives invalid text |
| `ReferenceError` | Using a variable that was never declared |
These types describe language-level failures. Your application's failures need their own types.
Creating a Custom Error Class
Extend Error and pass both message and options to super. The options argument is what keeps support for cause, which a later chapter covers.
class ValidationError extends Error {
constructor(message, options) {
super(message, options);
this.name = 'ValidationError';
}
}
const err = new ValidationError('Email is required');
console.log(err instanceof ValidationError); // true
console.log(err instanceof Error); // true
console.log(err.name); // 'ValidationError'
console.log(String(err)); // 'ValidationError: Email is required'Giving Your Error a Proper Name
If you leave out this.name = ..., the subclass inherits 'Error'. Logs and stack traces then show Error: Email is required, and you can't tell which class threw it.
Carrying Extra Data: Codes, Statuses, and Context
Callers often need structured data as well as the message text. Add that data as ordinary properties in the constructor:
class HttpError extends Error {
constructor(status, message, options) {
super(message, options);
this.name = 'HttpError';
this.status = status;
}
}
const err = new HttpError(503, 'Upstream unavailable');
console.log(err.status); // 503
console.log(err.message); // 'Upstream unavailable'A handler can then branch on err.status and doesn't have to parse the message. Unlike message and stack, custom fields like this are enumerable.
Exercise
A class DbError extends Error has a constructor that calls only super(message). Name two problems with it.
Show answer
The class never sets name, so String(err) and stack traces show Error and not DbError. The constructor also drops the options argument, so a cause passed by the caller is lost.