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 🙏

© 2025 – Pkg Stats / Ryan Hefner

express-error-toolkit

v1.2.1

Published

A lightweight and developer-friendly toolkit for robust error handling in Express.js applications. Includes ready-to-use custom error classes, an async route error handler wrapper, a global error handler middleware, and a convenient 'not found' route hand

Readme

express-error-toolkit

npm version typescript license downloads minified minified gzip

👉 View on npm

A lightweight, production-ready error handling toolkit for Express.js applications — written in TypeScript with full support for both CommonJS and ESM.

If you like the project, please give the project a GitHub ⭐

It provides:

  • Custom error classes (NotFoundError, BadRequestError, ValidationError, etc.)
  • Express middleware: globalErrorHandler, notFoundHandler
  • An asyncHandler utility to handle async errors without boilerplate
  • A httpError() factory function to create custom error instances easily
  • isCustomAPIError() type guard for safe error type checks

✨ Features

  • ✅ Type-safe custom error classes
  • ✅ Centralized error-handling middleware
  • ✅ Async error wrapper for route handlers
  • ✅ Built-in 404 (Not Found) handler
  • ✅ Factory method for generating custom errors
  • ✅ Type guard for runtime error checking
  • ✅ Out-of-the-box support for both CJS and ESM

🚀 Installation Guide

You can install express-error-toolkit using your favorite package manager.

Using npm

npm install express-error-toolkit

Using yarn

yarn add express-error-toolkit

Using pnpm

pnpm add express-error-toolkit

⚙️ Requires Node.js v14 or higher. ℹ️ Make sure you have express installed in your project, as this toolkit is built specifically to enhance Express.js error handling.


📁 Usage

1. asyncHandler: Wrap async route handlers

import express from 'express';
import { asyncHandler } from 'express-error-toolkit';

const app = express();

app.get(
  '/users/:id',
  asyncHandler(async (req, res) => {
    // Your async code here
    throw new Error('Something went wrong!');
  })
);

2. Custom Errors: Throw meaningful exceptions

import { NotFoundError, BadRequestError } from 'express-error-toolkit';

app.get('/test', (req, res) => {
  throw new NotFoundError('User not found');
});

Each custom error automatically sets the correct statusCode and name.

You can also pass optional errorDetails as a string, object, or leave it out:

throw new BadRequestError('Invalid data', { field: 'email' });
throw new BadRequestError('Invalid input', 'Missing required field');
throw new BadRequestError('Generic client error');

3. notFoundHandler: Catch unregistered routes

import { notFoundHandler } from 'express-error-toolkit';

app.use(notFoundHandler);

This will throw a NotFoundError with the method and route info.


4. globalErrorHandler: Handle all errors in one place

import { globalErrorHandler } from 'express-error-toolkit';

app.use(globalErrorHandler);

By default, the handler includes the stack trace and logs the error in development. In production (NODE_ENV=production), both are automatically suppressed for safety.


5. 🖍️ Readable Console Logs with ANSI Colors

To enhance developer experience during debugging, this toolkit uses ANSI escape codesno external dependencies like chalk required — to make console logs more readable.

Each part of the error log is styled using a traffic light-inspired color scheme:

  • 🔴 Error Status & Message – Red
  • 🟡 Error Details – Yellow (optional; string or object)
  • 🟢 Stack Trace – Green (shown only if available and enabled)

🖼️ Example: Here's how the console might look in development mode:

Colored error output preview


✨ Customizing the Intro Line

By default, an introductory line ("Even the best code breaks sometimes! Let's debug...") is displayed before each error block.

You can control this with the introLine option:

import { setErrorOptions } from 'express-error-toolkit';

// Disable the intro line
setErrorOptions({
  introLine: false
});

// Customize the intro line
setErrorOptions({
  introLine: '🚨 Debugging session begins here...'
});

6. Set Options Globally (Optional)

You can configure the error handling behavior (e.g., hide stack traces and disable console logging even in development) using either:

SHOW_STACK=false
LOG_ERROR=false

or directly in your code:

import { setErrorOptions } from 'express-error-toolkit';

setErrorOptions({
  showStack: false,
  logError: false
});

This overrides the default behavior (based on NODE_ENV or .env file).


7. httpError(): Create generic custom errors

import { httpError } from 'express-error-toolkit';

throw httpError('Something custom', 418);

You can also pass optional errorDetails as a string, object, or leave it out:

throw httpError('Expectation failed', 417,  { reason: 'The server could not meet the Expect header requirements' });
throw httpError('Failed Dependency', 424, 'This request relies on a previous request that failed' );
throw httpError('Unavailable for legal reason', 451);

8. isCustomAPIError(): Type guard for checking error type

import { isCustomAPIError } from 'express-error-toolkit';

if (isCustomAPIError(err)) {
  console.log(err.statusCode, err.message);
  // your rest of the code 
}

🔧 Custom Error Classes Available

| Error Class | Default Message | Status Code | |------------------------|-------------------------|-------------| | BadRequestError | Bad Request | 400 | | UnauthorizedError | Unauthorized | 401 | | ForbiddenError | Forbidden | 403 | | NotFoundError | Not Found | 404 | | ConflictError | Conflict | 409 | | ValidationError | Unprocessable Entity | 422 | | TooManyRequestsError | Too Many Requests | 429 | | CustomAPIError | Internal Server Error | 500 |


📂 Directory Structure

├── src/
│   ├── error/
│   │   ├── BadRequestError.ts
│   │   ├── NotFoundError.ts
│   │   └── ...
│   ├── global-error-handler.ts
│   ├── async-handler.ts
│   ├── http-error.ts
│   └── index.ts
├── example/
│   └── index.ts
├── __tests__/
│   └── *.test.ts

🛠 Build & Compatibility

  • Fully written in TypeScript
  • Outputs:
    • CommonJS: dist/index.cjs
    • ESM: dist/index.js
    • Types: dist/index.d.ts

📃 License

MIT © Rashedin Islam


🙌 Acknowledgements

This project includes http-status-toolkit, also created by me.

🤝 Contribution

We welcome contributions! Please check out the Contributing Guide.

Links


Made with ❤️ by Rashedin Islam