npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

express-error-tools

v1.0.0

Published

A lightweight, unopinionated, and highly effective global error-handling utility for Express.js applications.

Readme

express-error-tools

A lightweight, unopinionated, and highly effective global error-handling utility for Express.js applications.

npm version npm downloads License: ISC

Say goodbye to repetitive try/catch blocks in your route handlers! express-error-tools standardizes your API error responses, automatically handles asynchronous rejections, and provides a clean, seamless developer experience.


📖 Table of Contents


✨ Features

  • 🚀 Zero Boilerplate: Auto-patch Express routes to eliminate try/catch completely.
  • 🛠 Custom Error Class: Standardized Error class to handle operational errors with appropriate HTTP status codes.
  • 📦 Seamless Responses: Return the Response helper directly from your routes to send formatted JSON instantly.
  • 🛡 Production Ready: Hides sensitive stack traces in production environments while keeping them detailed in development.
  • ʦ TypeScript Native: Built with TypeScript, providing excellent out-of-the-box type definitions and IDE autocomplete.

📦 Installation

Install the package via npm:

npm install express-error-tools

🚀 Quick Start

The fastest and cleanest way to use express-error-tools is to patch Express globally. This allows you to write raw async/await routes without any wrappers or try/catch blocks.

import express from 'express';
import { patchExpress, createErrorHandler, Error, Response } from 'express-error-tools';

// 1. Patch Express (must be called before defining routes)
patchExpress();

const app = express();

// 2. Write clean, flat asynchronous routes
app.get('/users/:id', async (req, res) => {
  const user = await database.findById(req.params.id);
  
  if (!user) {
    // Throws a beautifully formatted 404 error
    throw new Error('User not found', 404);
  }
  
  // Instantly sends a 200 OK JSON response
  return Response("Successfully retrieved user", { user });
});

// 3. Mount the global error handler at the VERY END
app.use(createErrorHandler({
  defaultErrorMessage: "Internal server error",
  defaultStatusCode: 500,
  log: "dev" 
}));

app.listen(3000, () => console.log('Server running on port 3000'));

🧠 Core Concepts

1. Auto-Patching Express (Recommended)

Instead of wrapping every single route with a wrapper function, patchExpress() modifies Express internally to automatically catch errors for all routes.

import { patchExpress } from 'express-error-tools';

patchExpress(); // Call once at the root of your application

2. Seamless Success Responses

Inside any automatically patched route (or manually wrapped route), you can send successful JSON responses by simply returning the Response helper.

import { Response } from 'express-error-tools';

app.post('/users', async (req, res) => {
  const user = await database.create(req.body);
  
  // Triggers res.status(201).json(...) automatically
  return Response("User created", { user }, 201);
});

3. Manual Async Wrapping

If you prefer not to patch Express globally, you can manually wrap your asynchronous route handlers with catchAsync.

import { catchAsync } from 'express-error-tools';

app.post('/users', catchAsync(async (req, res, next) => {
  const user = await database.createUser(req.body);
  return Response("User created", { user }, 201);
}));

4. Throwing Operational Errors

Whenever you encounter an expected failure (e.g., validation failure, resource not found), throw an Error imported from the package. The global error handler will intercept it and format the response correctly.

import { Error } from 'express-error-tools';

if (invalidInput) {
    throw new Error('Validation failed', 400);
}

⚙️ Configuration

The createErrorHandler middleware must be mounted last in your Express application. It accepts a configuration object to customize its behavior:

app.use(createErrorHandler({
  defaultErrorMessage: "Internal server error", // Message sent when a non-operational error crashes the app
  defaultStatusCode: 500,                       // Status code for unknown errors
  log: "dev"                                    // Logging level: "dev" | "prod" | "none"
}));

📡 Response Formats

express-error-tools ensures all your API errors follow a predictable, standardized JSON structure.

Development Mode (NODE_ENV=development)

Provides detailed stack traces and raw error objects to help you debug quickly:

{
  "status": "error",
  "message": "Validation failed",
  "error": { ... },
  "stack": "Error: Validation failed\n    at /app/controllers/userController.js:14:11..."
}

Production Mode (NODE_ENV=production)

Automatically strips stack traces and prevents sensitive infrastructure details from leaking to the client:

{
  "status": "error",
  "message": "Validation failed"
}

(Note: If a non-operational programming error occurs, it is safely masked with your configured defaultErrorMessage).


📄 License

This project is licensed under the ISC License.