@satyajeetsahoo/exceptions
v2.1.3
Published
Typed application exceptions and centralized Express error handling
Maintainers
Readme
@satyajeetsahoo/exceptions
A standardized exception handling package for Node.js APIs.
Why use this package?
Inconsistent error responses across different API endpoints make it difficult for frontend clients to parse and handle errors gracefully. This package provides a centralized AppException class and a global error handling middleware to ensure every single error from your API follows the exact same JSON structure.
Features
- Standardized Format: Enforces a strict
{ success: false, error: { code, message, details } }structure. - HTTP Status Code Mapping: Automatically maps error codes (e.g.,
NOT_FOUND) to the correct HTTP status code. - Global Middleware: Catch all unhandled exceptions seamlessly in Express.
Installation
npm install @satyajeetsahoo/exceptionsUsage Examples
1. Throwing Application Exceptions
Instead of throwing generic Error objects, throw an AppException with a specific code and HTTP status.
import { AppException } from '@satyajeetsahoo/exceptions';
// In your controller or service
if (!user) {
throw new AppException('User not found', 404, 'USER_NOT_FOUND', { userId: 123 });
}2. Express Global Error Handler
Attach this middleware at the very end of your Express routes to intercept and format all errors.
import express from 'express';
import { errorHandler } from '@satyajeetsahoo/exceptions';
import { logger } from '@satyajeetsahoo/logger';
const app = express();
// ... your routes ...
// Global error handler
app.use(errorHandler(logger));Output JSON Format
When an error is thrown, the frontend receives a predictable payload:
{
"success": false,
"error": {
"code": "USER_NOT_FOUND",
"message": "User not found",
"details": { "userId": 123 },
"traceId": "req-1234-abcd"
}
}