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
yarn add express-errorkit
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();
initSentry({
dsn: process.env.SENTRY_DSN,
environment: process.env.NODE_ENV || "development",
enabled: true,
});
app.get("/users/:id", async (req, res, next) => {
try {
const user = null;
if (!user)
throw new NotFoundError({
message: "User not found",
metadata: { id: req.params.id },
});
res.json(user);
} catch (err) {
next(err);
}
});
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);
}
});
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