exception-handler-express
v1.1.0
Published
A robust, extensible exception handling library for Node.js and Express. Provides typed HTTP exceptions, automatic error formatting, and optional Sentry integration out of the box.
Maintainers
Readme
exception-handler-express
A robust, extensible exception handling library for Node.js and Express. Provides typed HTTP exception classes, automatic error formatting, and optional Sentry integration out of the box.
Features
- 🎯 Typed HTTP Exceptions —
BadRequest,NotFound,Unauthorized,Forbidden,Conflict, and many more - 🛡️ Express Error Middleware — Drop-in middleware that catches errors, formats responses, and reports to Sentry
- 📡 Sentry Integration — Optional built-in Sentry error reporting with breadcrumb filtering and header sanitization
- 🔌 Extensible — Bring your own error reporter by implementing
IErrorReporter - 🧩 Dual Module — Ships both ESM and CommonJS builds with full TypeScript declarations
- ⚡ Axios Support — Automatically wraps
AxiosErrorresponses into structured API errors
Installation
npm install exception-handler-expressPeer Dependencies
The following are optional peer dependencies — install only what you need:
# Required if using the ExceptionHandler middleware
npm install express
# Required if using the built-in Sentry reporter
npm install @sentry/node
# Required if using ApiError / Axios error wrapping
npm install axiosQuick Start
1. Throw Typed Exceptions
import { Exceptions } from 'exception-handler-express';
// In your route handler
app.get('/users/:id', async (req, res) => {
const user = await findUser(req.params.id);
if (!user) {
throw new Exceptions.NotFound('User not found');
}
// With custom error code and metadata
if (!user.isActive) {
throw new Exceptions.Forbidden('Account suspended', {
errorCode: 'ACCOUNT_SUSPENDED',
data: { userId: user.id },
});
}
res.json(user);
});2. Add the Error Middleware
import express from 'express';
import { ExceptionHandler } from 'exception-handler-express';
const app = express();
// ... your routes ...
// Add as the LAST middleware (after all routes)
app.use(ExceptionHandler.middleware());3. Enable Sentry Reporting (Optional)
import { ExceptionHandler, SentryReporterFactory } from 'exception-handler-express';
// Option A: Auto-configure via environment variable
// Set SENTRY_DSN in your env, and the middleware picks it up automatically
app.use(ExceptionHandler.middleware());
// Option B: Explicit configuration
const reporter = SentryReporterFactory.createInstance({
dsn: 'https://your-sentry-dsn',
});
app.use(ExceptionHandler.middleware(false, reporter));API Reference
Exception Classes
All exceptions extend BaseException and include an HTTP status code, error code, and optional metadata.
| Exception | Status Code | Default Error Code |
| ----------------------- | ----------- | ------------------------ |
| BadRequest | 400 | BAD_REQUEST |
| Unauthorized | 401 | UNAUTHORIZED |
| Forbidden | 403 | FORBIDDEN |
| NotFound | 404 | NOT_FOUND |
| MethodNotAllowed | 405 | METHOD_NOT_ALLOWED |
| NotAcceptable | 406 | NOT_ACCEPTABLE |
| RequestTimeout | 408 | REQUEST_TIMEOUT |
| Conflict | 409 | CONFLICT |
| PayloadTooLarge | 413 | PAYLOAD_TOO_LARGE |
| UnsupportedMediaType | 415 | UNSUPPORTED_MEDIA_TYPE |
| TooManyRequests | 429 | TOO_MANY_REQUESTS |
| InternalServerError | 500 | INTERNAL_SERVER_ERROR |
| NotImplemented | 501 | NOT_IMPLEMENTED |
| BadGateway | 502 | BAD_GATEWAY |
| ServiceUnavailable | 503 | SERVICE_UNAVAILABLE |
| ApiError | varies | from Axios response |
Constructor
new BadRequest(message: string, metaData?: IErrorMetaData)message— Human-readable error messagemetaData.errorCode— Override the default error code stringmetaData.data— Attach arbitrary data to the error response
Error Response Format
{
"code": "NOT_FOUND",
"message": "User not found",
"traceId": "a1b2c3d4-...",
"data": {}
}In non-production environments (NODE_ENV !== 'production'), stack traces and error names are included in data.
ExceptionHandler.middleware(showStackTrace?, reporter?)
Express error-handling middleware.
| Parameter | Type | Default | Description |
| ---------------- | ----------------- | ----------------------------- | ------------------------------------------------ |
| showStackTrace | boolean | false | Force stack traces in responses |
| reporter | IErrorReporter | Sentry (if SENTRY_DSN set) | Custom error reporter instance |
Behaviour:
- Catches
BaseExceptioninstances and formats them into JSON responses - Wraps
AxiosErrorinstances intoApiError - Wraps unknown errors into
InternalServerError - Reports 5xx errors to the configured reporter (if any)
- Attaches a unique
traceIdto every error response
SentryReporterFactory
Factory for creating Sentry reporter instances.
// Auto-detect from SENTRY_DSN env var
const reporter = SentryReporterFactory.getInstance();
// Explicit configuration
const reporter = SentryReporterFactory.createInstance({
dsn: 'https://...',
filterBreadcrumbs: (breadcrumb) => breadcrumb,
beforeReport: (event) => event,
});Custom Error Reporter
Implement the IErrorReporter interface to use your own reporting service:
import { IErrorReporter, IErrorReportScopes } from 'exception-handler-express';
class CustomReporter implements IErrorReporter {
reportEvent(event: Object, scopes?: IErrorReportScopes): void {
// Send to your monitoring service
}
reportMessage(message: string, scopes?: IErrorReportScopes): void {
// Send to your monitoring service
}
reportException(error: Error | unknown, scopes?: IErrorReportScopes): void {
// Send to your monitoring service
}
}
app.use(ExceptionHandler.middleware(false, new CustomReporter()));Enums
HttpStatusCode
Standard HTTP status codes (100–505).
HttpErrorCode
String error code identifiers matching the exception classes.
Exports
import {
// Exception classes (namespaced)
Exceptions,
// Middleware
ExceptionHandler,
// Sentry integration
SentryReporterFactory,
// Enums
HttpStatusCode,
HttpErrorCode,
// Types
IErrorReporterOptions,
} from '@automatonatm/exceptionhandler';
// Access individual exceptions
const { BadRequest, NotFound, Unauthorized } = Exceptions;Environment Variables
| Variable | Description | Required |
| ----------------- | ------------------------------------ | -------- |
| NODE_ENV | Controls stack trace visibility | No |
| SENTRY_DSN | Auto-enables Sentry reporting | No |
| SENTRY_RELEASE | Sets the Sentry release tag | No |
