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-errorkitIf you're using Sentry reporting, also install
@sentry/nodein 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 messagestatus— HTTP status (default500)shouldReport— Whether to report to Sentry (defaulttrue)metadata— Structured context (default{})code— Machine-readable error code (defaultAPP_ERROR)userMessage— Safe client-facing message (defaultSomething 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,
});errorLoggerlogs structured errors tostderr.errorRespondersends 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:
AppErrorNotFoundError(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
