0
0
Expressframework~5 mins

Custom error classes in Express

Choose your learning style9 modes available
Introduction

Custom error classes help you create specific error types. This makes your code easier to understand and handle errors better.

When you want to handle different errors in different ways in your Express app.
When you want to add extra information to errors, like status codes.
When you want to keep your error handling clean and organized.
When you want to send clear error messages to users or logs.
Syntax
Express
class CustomError extends Error {
  constructor(message) {
    super(message);
    this.name = 'CustomError';
    this.statusCode = 400; // example status code
  }
}

Always extend the built-in Error class.

Set this.name to your custom error name for easier identification.

Examples
This error represents a 'Not Found' situation with status code 404.
Express
class NotFoundError extends Error {
  constructor(message) {
    super(message);
    this.name = 'NotFoundError';
    this.statusCode = 404;
  }
}
This error is for validation problems with status code 422.
Express
class ValidationError extends Error {
  constructor(message) {
    super(message);
    this.name = 'ValidationError';
    this.statusCode = 422;
  }
}
Sample Program

This Express app uses a custom NotFoundError. When an item is missing, it sends a 404 error with a clear message.

Express
import express from 'express';

class NotFoundError extends Error {
  constructor(message) {
    super(message);
    this.name = 'NotFoundError';
    this.statusCode = 404;
  }
}

const app = express();

app.get('/item/:id', (req, res, next) => {
  const item = null; // pretend we searched but found nothing
  if (!item) {
    return next(new NotFoundError('Item not found'));
  }
  res.send(item);
});

app.use((err, req, res, next) => {
  if (err instanceof NotFoundError) {
    return res.status(err.statusCode).json({ error: err.message });
  }
  res.status(500).json({ error: 'Internal Server Error' });
});

export default app;
OutputSuccess
Important Notes

Use instanceof to check for your custom error type in middleware.

Always call super(message) in the constructor to set the error message.

Custom errors help keep your error handling clear and consistent.

Summary

Custom error classes extend the built-in Error to add specific error types.

They help you send proper status codes and messages in Express apps.

Use them to organize and improve your error handling.