0
0
ExpressHow-ToBeginner · 3 min read

How to Create a Custom Error Class in Express

To create a custom error class in Express, extend the built-in Error class with your own class that sets a statusCode and message. Then throw this error in your routes and handle it in an error middleware to send proper responses.
📐

Syntax

Create a class that extends Error. Use super(message) to set the error message. Add a statusCode property to represent HTTP status codes.

This custom error can then be thrown in your Express routes.

javascript
class CustomError extends Error {
  constructor(message, statusCode) {
    super(message);
    this.statusCode = statusCode;
    Error.captureStackTrace(this, this.constructor);
  }
}
💻

Example

This example shows a simple Express app with a custom error class. The app throws a NotFoundError when a route is not found, and the error middleware sends a JSON response with the error message and status code.

javascript
import express from 'express';

class NotFoundError extends Error {
  constructor(message = 'Resource not found') {
    super(message);
    this.statusCode = 404;
    Error.captureStackTrace(this, this.constructor);
  }
}

const app = express();

app.get('/', (req, res) => {
  res.send('Hello World');
});

app.get('/error', (req, res, next) => {
  next(new NotFoundError());
});

// Error handling middleware
app.use((err, req, res, next) => {
  const status = err.statusCode || 500;
  res.status(status).json({
    error: err.message || 'Internal Server Error'
  });
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
Output
Server running on http://localhost:3000 Request to /error returns HTTP 404 with JSON: {"error":"Resource not found"}
⚠️

Common Pitfalls

  • Not calling super(message) in the constructor causes the error message to be missing.
  • Forgetting to set statusCode means your error handler may default to 500, hiding the real error type.
  • Not using an error-handling middleware in Express will cause unhandled errors and crash the app.
javascript
/* Wrong way: Missing super call and statusCode */
class BadError extends Error {
  constructor(message) {
    super(message);
    this.message = message; // super call added
  }
}

/* Right way: */
class GoodError extends Error {
  constructor(message, statusCode) {
    super(message);
    this.statusCode = statusCode;
  }
}
📊

Quick Reference

Tips for custom errors in Express:

  • Always extend Error and call super(message).
  • Set a statusCode property for HTTP status.
  • Use Error.captureStackTrace for better stack traces.
  • Throw your custom errors in routes and handle them in error middleware.

Key Takeaways

Create custom errors by extending the built-in Error class and setting a statusCode.
Always call super(message) in your custom error constructor to set the message properly.
Use Express error-handling middleware to catch and respond to custom errors.
Setting statusCode helps send correct HTTP responses for different error types.
Capture stack trace with Error.captureStackTrace for clearer debugging.