api-error-kit
v0.1.0
Published
A lightweight error-handling toolkit for Node.js and Express applications.
Maintainers
Readme
api-error-kit
A lightweight error-handling toolkit for Node.js and Express applications. It provides a consistent HTTP error class, centralized Express error middleware, and an async route-handler wrapper.
- Zero runtime dependencies
- CommonJS and ES Module exports
- TypeScript declarations included
- Compatible with Express 4 and Express 5
- Requires Node.js 18 or newer
Installation
npm install api-error-kitInstall Express separately in your application:
npm install expressapi-error-kit does not install or bundle Express for you.
Quick start (CommonJS)
const express = require('express');
const {
HttpError,
asyncHandler,
errorHandler
} = require('api-error-kit');
const app = express();
app.get('/users/:id', asyncHandler(async (req, res) => {
const user = null; // Replace with your database lookup.
if (!user) {
throw new HttpError(404, 'User not found', {
code: 'USER_NOT_FOUND'
});
}
res.json({ success: true, data: user });
}));
// Always register the error handler after your routes.
app.use(errorHandler());
app.listen(3000);A missing user produces this JSON response with HTTP status 404:
{
"success": false,
"error": {
"status": 404,
"code": "USER_NOT_FOUND",
"message": "User not found"
}
}API
new HttpError(statusCode, message, options?)
Create an intentional HTTP error that errorHandler can safely serialize.
throw new HttpError(422, 'Email is invalid', {
code: 'EMAIL_INVALID',
details: { field: 'email' }
});statusCode: integer from400through599.message: non-empty, public-facing message.options.code: optional uppercase error code. If omitted, a default is selected from the status code.options.details: optional structured information. It is not returned unlessexposeDetailsis enabled.options.cause: optional original error, available aserror.cause.
Default status-to-code mappings include 400 BAD_REQUEST, 401 UNAUTHORIZED, 403 FORBIDDEN, 404 NOT_FOUND, 409 CONFLICT, 422 UNPROCESSABLE_ENTITY, 429 TOO_MANY_REQUESTS, and 500 INTERNAL_SERVER_ERROR. Other valid status codes use HTTP_ERROR unless a custom code is supplied.
errorHandler(options?)
Returns Express error-handling middleware. Place it after all routes and other middleware that may call next(error).
app.use(errorHandler());Options:
| Option | Default | Description |
| --- | --- | --- |
| exposeDetails | false | Include details from HttpError in the JSON response. |
| exposeUnknownErrors | false | Include the message from errors that are not HttpError instances. Use only in development. |
Unknown errors are converted to a generic 500 Internal Server Error response by default. Their original messages and stack traces are not sent to clients. HttpError messages are treated as public-facing messages and are returned to the client.
If response headers have already been sent, the middleware forwards the error to Express using next(error).
asyncHandler(handler)
Wrap an Express route handler so both synchronous exceptions and rejected promises are passed to Express error middleware.
app.get('/profile', asyncHandler(async (req, res) => {
const profile = await loadProfile();
if (!profile) {
throw new HttpError(404, 'Profile not found');
}
res.json(profile);
}));This wrapper works with Express 4 and Express 5. Express 5 forwards rejected route-handler promises automatically, but this wrapper can still be used for consistent behavior across both versions.
ES Modules
import express from 'express';
import { HttpError, asyncHandler, errorHandler } from 'api-error-kit';
const app = express();
app.get('/items/:id', asyncHandler(async (req, res) => {
throw new HttpError(404, 'Item not found');
}));
app.use(errorHandler());
app.listen(3000);Development-only error messages
You can expose unknown error messages while developing, but do not enable this in production because messages may contain internal implementation details.
app.use(errorHandler({
exposeUnknownErrors: process.env.NODE_ENV !== 'production'
}));Only enable exposeDetails when the details are safe for clients to see. Avoid placing secrets, tokens, database records, or personal data in error details.
TypeScript
Type declarations are included. No separate @types package is required for api-error-kit.
import { HttpError, errorHandler } from 'api-error-kit';
const error = new HttpError(404, 'Order not found', {
code: 'ORDER_NOT_FOUND'
});
app.use(errorHandler());Running the tests
Clone the repository, then run:
npm test
npm run check
npm run pack:checkThe test suite uses Node.js's built-in test runner and requires no test dependencies.
License
MIT. See LICENSE.
