Overview

Centralized error handling for your Express app. Catches all unhandled errors.

Features

  • Global error catching
  • Environment-aware responses
  • Error logging
  • Custom error classes

Installation

npx hanma add error-middleware

Code

import { Request, Response, NextFunction } from "express";

export const errorHandler = (
  err: Error,
  _req: Request,
  res: Response,
  _next: NextFunction
) => {
  console.error("[ERROR]", err.stack || err.message);
  res.status(500).json({
    success: false,
    message:
      process.env.NODE_ENV === "development"
        ? err.message
        : "Internal Server Error",
  });
};

export const notFoundHandler = (req: Request, res: Response) => {
  res.status(404).json({
    success: false,
    message: "Resource not found",
    path: req.originalUrl,
  });
};

Usage

import { errorHandler, AppError } from './middleware/error-middleware';

// Must be last middleware
app.use(errorHandler);

// Throw custom errors
throw new AppError('Not found', 404);

Dependencies

No external dependencies required.

Frequently Asked Questions

How do I install Error Handler?
Run the following command: npx hanma add error-middleware
How do I use this snippet?
Copy the code and paste it into your project. The snippet will be saved to middleware/error-middleware.ts.
Can I customize this snippet?
Yes! All snippets are copy-paste code that you own. Feel free to modify them to fit your needs.
Does this work with other frameworks?
This snippet is designed for the specific framework. Check the other framework pages for equivalent implementations.