New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details
Socket
Book a DemoSign in
Socket

express-errorkit

Package Overview
Dependencies
Maintainers
1
Versions
4
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

express-errorkit

Simple Express middleware for handling errors

latest
npmnpm
Version
1.1.1
Version published
Maintainers
1
Created
Source

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

FAQs

Package last updated on 30 Aug 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts