Sub topic 16
Choosing Between Error Classes and Error Codes
This chapter assumes you already know how to subclass Error, set name, add fields such as status, and check errors with instanceof. Here the question is a design one: when a new failure case comes up, should it get its own class, or a code value on an existing class?
Two ways to say what went wrong
A custom class encodes the kind of failure in the prototype chain. You check it with instanceof. An error code encodes the kind of failure in a string field, and you check it with ===. Node.js mostly uses codes. For example, a missing file produces a plain Error whose code is 'ENOENT'.
| Concern | Error class | Error code |
|---|---|---|
| How it is checked | `err instanceof X` | `err.code === 'X'` |
| Survives JSON and network hops | No, the prototype is lost | Yes, it is just a string |
| Works across duplicate package copies or realms | Can fail | Always works |
| Carries its own fields and constructor logic | Yes | Only through shared fields |
| Cost of adding a case | A new class | A new string constant |
| Groups related failures | Yes, through inheritance | Only through naming conventions |
A hybrid that usually wins
Most codebases do well with a small number of classes, one per way the caller responds, and a code field for the fine-grained reason inside each class.
class AppError extends Error {
constructor(code, message, options) {
super(message, options);
this.name = 'AppError';
this.code = code;
}
}
class PaymentError extends AppError {
constructor(code, message, options) {
super(code, message, options);
this.name = 'PaymentError';
}
}
function describe(err) {
if (err instanceof PaymentError) {
switch (err.code) {
case 'CARD_DECLINED':
return 'Ask the user for another card';
case 'INSUFFICIENT_FUNDS':
return 'Show a balance warning';
default:
return 'Payment failed, try again later';
}
}
throw err;
}
console.log(describe(new PaymentError('CARD_DECLINED', 'Card was declined')));
// 'Ask the user for another card'The class answers "which handler owns this?" and the code answers "which branch inside that handler?". The code also stays readable after the error is serialized or sent to another service.
Deciding for a new failure case
Guidelines
- Keep hierarchies shallow. Two or three levels are enough. Deep trees make
catchblocks harder to order correctly. - Name classes after what failed, such as
PaymentError. Avoid names that describe where the error was thrown. - Treat codes as public API. Use stable, uppercase strings, document them, and never reuse one for a different meaning.
- Don't create a class just to hold a different message. If the handler is the same, use the same class.
- When you wrap errors at a layer boundary, keep the original in
causeand give the wrapper its own class or code. - In code that may receive errors from other packages or realms, check
err?.codeas a fallback, becauseinstanceofcan fail there.
Exercise
Your HTTP client can fail with timeouts, DNS failures, connection resets, and TLS errors. Callers retry all four the same way, but they treat 4xx responses differently. How would you model these errors?
Show answer
Create one NetworkError class with codes such as 'TIMEOUT', 'DNSFAILURE', 'ECONNRESET', and 'TLSERROR', because callers handle all four the same way. Create a separate HttpError class with a status field for 4xx and 5xx responses, because callers branch on it and it carries its own data. Keep the low-level error in cause in both cases.