@mayur-00/express-api-error-handler
v1.0.3
Published
A lightweight Express error-handling utility for returning consistent JSON error responses from your API.
Downloads
101
Readme
Express API Error Handler
A lightweight Express error-handling utility for returning consistent JSON error responses from your API.
This package exposes:
ApiErrorfor structured application errorshandleErrormiddleware for catching and formatting thrown errors- a predictable API response shape for client and server errors
Features
- Standardizes API error payloads
- Preserves HTTP status codes
- Supports custom error codes and validation details
- Adds stack traces only in development mode
- Works as an Express error middleware
Installation
npm install @mayur-00/express-api-error-handlerBasic usage
import express from 'express';
import { ApiError, handleError } from '@mayur-00/express-api-error-handler';
const app = express();
app.get('/users/:id', async (req, res) => {
const userId = req.params.id;
if (!userId) {
throw new ApiError(400, 'User ID is required', 'VALIDATION_ERROR', [
'Missing userId in request path',
]);
}
const user = { id: userId, name: 'Jane Doe' };
res.json({ success: true, data: user });
});
// just add at the end of your routes and other specification in index file
app.use(handleError);
app.listen(3000, () => {
console.log('Server started on http://localhost:3000');
});Creating custom errors
import { ApiError } from '@mayur-00/express-api-error-handler';
throw new ApiError(
404,
'User not found',
'USER_NOT_FOUND',
[{ field: 'id', message: 'No user exists for the given id' }],
);API reference
ApiError
new ApiError(
statusCode: number,
message = 'Something Went wrong',
error_code = 'IMPLEMENTATION_ERROR',
errors: unknown[] = [],
stack = '',
)Properties:
statusCode: HTTP response status codemessage: human-readable error messagedata: alwaysnullin this implementationsuccess: alwaysfalseerrors: array of error detailserror_code: custom error identifierstack: stack trace string in development mode or captured automatically
handleError
handleError(err, req, res, next)The middleware:
- Accepts an error object from Express
- Normalizes any non-
ApiErrorvalues into anApiError - Uses the error's
statusCodeif available, otherwise defaults to500 - Returns a consistent JSON response
Response format
The error handler responds with this structure:
{
"success": false,
"message": "User not found",
"error_code": "USER_NOT_FOUND",
"errors": [
{ "field": "id", "message": "No user exists for the given id" }
],
"stack": "Error: User not found\n at ..."
}Notes:
stackis included only whenNODE_ENV === 'development'errorsis an empty array by defaulterror_codedefaults toSERVER_ERRORfor unknown exceptions
Notes
This package is designed for Express-based Node.js APIs and follows a simple convention for returning structured JSON errors rather than raw stack traces to clients.
License
ISC
