Skip to content
tezvyn:

Custom Error Classes: Beyond Generic Errors

Source: developer.mozilla.orgEasyHow cards are made

Custom Error Classes: Beyond Generic Errors

Create specific error types, like NotFoundError, instead of generic ones. This lets your code react differently to different failures, like sending a 404 for a missing user vs. a 500 for a database outage.

Why it exists

JavaScript provides a generic Error object, but real applications have many distinct failure modes. A "user not found" error is fundamentally different from a "database connection failed" error. Relying on string matching error messages is brittle and error-prone. Custom error classes solve this by creating explicit, typed categories for failures.

The mental model

Think of custom errors like HTTP status codes. Instead of just "error" (like a generic 500), you have specific signals like 404 Not Found, 400 Bad Request, or 503 Service Unavailable. This allows consuming code, like an Express error-handling middleware, to know exactly what kind of response to send without inspecting the error message string.

How it works

You create a new class that extends the built-in Error class. The constructor for your custom class must call super() to properly initialize the parent Error object, passing the error message to it. This ensures your custom error inherits standard properties like message and a proper stack trace. You can then set a custom name property and add other properties, like a statusCode, to carry more context. For example: class NotFoundError extends Error { constructor(message) { super(message); this.name = 'NotFoundError'; this.statusCode = 404; } }.

When to use it

Use custom errors to differentiate between operational errors (expected failures, like invalid user input) and programmer errors (bugs). They are essential in API development for mapping specific failures to appropriate HTTP status codes. For instance, a ValidationError can map to a 400 response, while an AuthenticationError maps to a 401.

When not to use it

For simple scripts or small projects where there are only one or two expected failure types, a generic new Error('message') might be sufficient. Over-engineering with dozens of custom error classes for a small utility can add unnecessary complexity. The goal is clarity, not classification for its own sake.

One canonical example

In an Express.js API, a central error-handling middleware can inspect the type of error it receives. If a service throws new UserNotFoundError('User 123 not found'), the middleware can check if (err instanceof UserNotFoundError) and reliably send a 404 status code. If it catches a generic Error, it can default to a 500 Internal Server Error. This avoids fragile logic like if (err.message.includes('not found')).

Interview question

What is the primary benefit of implementing custom error classes in an application, especially for APIs?

  • a.They reduce the need for try...catch blocks by handling errors implicitly.
  • b.They simplify error messages by standardizing them across the application.
  • c.They automatically prevent the application from crashing when an error occurs.
  • d.They allow for reliable, type-based differentiation of failure modes, enabling specific responses.Correct
Why?

The card emphasizes that custom error classes provide explicit, typed categories for failures, allowing consuming code (like API middleware) to reliably differentiate between various failure types (e.g., using 'instanceof') and send appropriate responses. While preventing crashes is a goal of error handling, it's not the primary, unique benefit of *custom* error classes over generic ones, which also allow for caught errors.

Just read this? Test yourself on what you have been reading.

Read the original → developer.mozilla.org

You just looked this up. Could you explain it out loud?

That is the part interviews actually test. Tezvyn takes questions like this one and gives you what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on javascript — each one lists the topics its interview covers.

See open roles