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-errorkit

v1.1.1

Published

Simple Express middleware for handling errors

Readme

express-errorkit

A flexible error handling toolkit for Express.js applications that simplifies managing errors and logging, with built-in Sentry integration and structured logging.

Installation

npm install express-errorkit
# or
yarn add express-errorkit
# or
pnpm add express-errorkit

If you're using Sentry reporting, also install @sentry/node in your project.

npm install @sentry/node

Quick Start

Express Integration

const express = require("express");
const {
  AppError,
  NotFoundError,
  ValidationError,
  createErrorMiddleware,
  initSentry,
} = require("express-errorkit");

const app = express();

// (Optional) Initialize Sentry in production environments
initSentry({
  dsn: process.env.SENTRY_DSN,
  environment: process.env.NODE_ENV || "development",
  enabled: true, // Set false to disable
});

// Example route that throws a NotFoundError
app.get("/users/:id", async (req, res, next) => {
  try {
    const user = null; // Simulating a user lookup
    if (!user)
      throw new NotFoundError({
        message: "User not found",
        metadata: { id: req.params.id },
      });
    res.json(user);
  } catch (err) {
    next(err);
  }
});

// Example route for validation errors
app.post("/login", (req, res, next) => {
  try {
    const { email, password } = req.body;
    if (!email || !password) {
      throw new ValidationError({
        message: "Missing email or password",
        metadata: { emailPresent: !!email, passwordPresent: !!password },
      });
    }
    res.json({ ok: true });
  } catch (err) {
    next(err);
  }
});

// Error middleware
const { errorLogger, errorResponder } = createErrorMiddleware({
  prodLikeEnvs: ["production", "localprod"],
  reportInProdOnly: true,
});

app.use(errorLogger);
app.use(errorResponder);

app.listen(3000, () => {
  console.log("API listening on http://localhost:3000");
});

Error Classes

All errors now accept an object as the constructor parameter. You can provide:

  • message — Error message
  • status — HTTP status (default 500)
  • shouldReport — Whether to report to Sentry (default true)
  • metadata — Structured context (default {})
  • code — Machine-readable error code (default APP_ERROR)
  • userMessage — Safe client-facing message (default Something went wrong.)

Example:

throw new NotFoundError({
  message: "User not found",
  metadata: { userId: req.params.id },
});

Middleware

const { createErrorMiddleware } = require("express-errorkit");
const { errorLogger, errorResponder } = createErrorMiddleware({
  prodLikeEnvs: ["production", "localprod"],
  reportInProdOnly: true,
});
  • errorLogger logs structured errors to stderr.
  • errorResponder sends the error response in JSON format, with different handling based on environment (development vs production-like environments).

Sentry Integration

const { initSentry } = require("express-errorkit");

initSentry({
  dsn: process.env.SENTRY_DSN,
  environment: process.env.NODE_ENV || "development",
  enabled: true,
});

If @sentry/node is installed and configured, errors will be reported to Sentry as per the shouldReport flag and environment configuration.

Logging

Errors are logged as structured JSON lines, which can easily be integrated with log aggregators like Datadog, CloudWatch, or ELK.

Example log output:

{
  "message": "User not found",
  "status": 404,
  "code": "NOT_FOUND",
  "metadata": { "id": "u_123" },
  "stack": "Error: ...",
  "requestId": "req-abc123"
}

API

Error Classes

Each class extends AppError and provides useful defaults for specific HTTP statuses:

  • AppError
  • NotFoundError (404)
  • ValidationError (400)
  • AuthError (401/403)
  • PermissionError (403)
  • ConflictError (409)
  • RateLimitError (429)
  • ServerError (500)
  • ServiceUnavailableError (503)
  • TimeoutError (504)

TypeScript Support

This package is fully typed using JSDoc and can be easily used in TypeScript projects.


License

MIT