error-guard
v2.0.1
Published
Error Guard is a lightweight, TypeScript-friendly library for standardized error handling in Node.js/Express applications.
Maintainers
Readme
🛡️ Error Guard
Error Guard is a lightweight, TypeScript-friendly library for standardized error handling in Node.js/Express applications.
🔄 Latest Update (v2.0.1)
ErrorGuard is now 10% faster! See full details in the CHANGELOG.md.
Installation
npm install error-guardEnvironment Variables
- Make sure you have a variable named
NODE_ENVin your.envfile. - When
process.env.NODE_ENV !== 'production', all error objects include a full stack trace to help with debugging. - In production, the stack field is automatically removed to prevent sensitive information from being exposed in API responses.
It provides:
- Custom error classes with HTTP status codes and error codes
- Predefined error helpers (BadRequest, ValidationError, etc.)
- Async route handler wrapper
- Express error-handling middleware
Usage
- Basic Example
import express from "express";
import {
BadRequest,
asyncHandler,
createErrorHandler,
} from "error-guard";
const app = express();
app.use(express.json());
app.get(
"/test",
asyncHandler(async (req, res) => {
// Throw a standardized error
throw BadRequest("Invalid request data");
})
);
// Global error handler
app.use(createErrorHandler());
app.listen(3000, () => console.log("Server running on port 3000"));- Output (JSON):
{
"status": "fail",
"code": "BAD_REQUEST",
"message": "Invalid request data",
"stack": "Error: ...",
}Using Predefined Errors
BadRequest(message, details): Invalid request dataValidationError(message, details): Schema or input validation failedAuthenticationError(message, details): Invalid or missing credentialsAuthorizationError(message, details): Not allowed to perform this actionResourceNotFound(message, details): Resource does not existConflictError(message, details): Conflict with an existing resourceRateLimitError(message, details): Too many requestsDependencyError(message, details): External dependency failedInternalError(message, details): Generic server error
BadRequest(message?: string, details?: any)
ValidationError(message?: string, details?: any)
AuthenticationError(message?: string, details?: any).You can also provide optional details for more information:
throw ValidationError("Invalid email format", { field: "email" });Async Handlers
- Wrap async route handlers to automatically catch errors:
app.get(
"/async-test",
asyncHandler(async (req, res) => {
const data = await fetchData();
if (!data) throw ResourceNotFound("Data not found");
res.json(data);
})
);Custom Error Handling Middleware
- You can provide a logger to capture all errors:
app.use(createErrorHandler({
logger: (err, req) => {
console.error(`[${req.method}] ${req.url} -`, err);
}
}));API Reference
new ErrorGuard(statusCode?: number, code?: string, message?: string, details?: any)statusCode— HTTP status code (default: 500)code— Error code string (default: "ERROR")message— Error messagedetails— Optional extra information
License
MIT License © l1l-01
