Skip to content

Error-Cure: A powerful error handling library for Node.js and Express. Provides custom error classes, global middleware, logging utilities, and tools for managing unhandled exceptions. Simplify and centralize error management for robust applications.

License

Notifications You must be signed in to change notification settings

AkshayPanchivala/error-cure

Repository files navigation

πŸš€ Error-Cure: The Ultimate Error Handling Solution for Node.js & Express

NPM Version NPM Downloads License

Tired of messy error handling, inconsistent API responses, and fragile Node.js applications? Error-Cure is your one-stop solution for building robust, production-ready, and developer-friendly APIs with Express.

Error-Cure provides a comprehensive suite of tools to streamline your error handling workflow, from custom error classes to a powerful global middleware. It's designed to be lightweight, easy to use, and highly configurable, allowing you to focus on what matters most: building great applications.

πŸ€” Why Error-Cure?

Feature Benefit
Centralized Handling Manage all errors in one place, ensuring consistent and predictable API responses.
Improved Debugging Differentiate between operational errors (user-facing) and programming errors (internal bugs).
Enhanced User Experience Provide clear, meaningful error messages to your users without exposing sensitive stack traces.
Increased Stability Gracefully handle unhandled promise rejections and uncaught exceptions to prevent crashes.
Accelerated Development Reduce boilerplate code and focus on your core application logic.
TypeScript & JS Support Seamlessly integrate with both TypeScript and JavaScript projects (CommonJS & ESM).

✨ Features

  • πŸ”ͺ Custom Error Classes: A set of pre-built, extensible error classes for common scenarios:
    • AppError: The base class for all operational errors.
    • ValidationError: For input validation failures (400).
    • AuthError: For authentication/authorization issues (401).
    • NotFoundError: For missing resources (404).
    • DatabaseError: For database-related failures (500).
  • πŸ›‘οΈ Global Error Middleware: A powerful Express middleware that catches all errors and sends beautiful, environment-aware responses.
  • πŸ“ Error Logging: A simple yet effective utility to log errors to a file for easy debugging and monitoring.
  • 🚨 Unhandled Rejection/Exception Handling: Automatically catches and logs unhandled promise rejections and uncaught exceptions.
  • βœ… TypeScript Ready: Written entirely in TypeScript with type definitions included.
  • πŸ“¦ Dual Module Support: Supports both CommonJS (require) and ES Modules (import).

πŸ“¦ Installation

# Using npm
npm install error-cure

# Using yarn
yarn add error-cure

πŸ“‚ Project Structure

error-cure/
β”œβ”€β”€ dist/
β”‚   β”œβ”€β”€ cjs/                # CommonJS output
β”‚   └── esm/                # ES Module output
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ index.ts            # Main entry point
β”‚   β”œβ”€β”€ errors/
β”‚   β”‚   β”œβ”€β”€ AppError.ts
β”‚   β”‚   β”œβ”€β”€ AuthError.ts
β”‚   β”‚   β”œβ”€β”€ DataBaseError.ts
β”‚   β”‚   β”œβ”€β”€ NotFoundError.ts
β”‚   β”‚   └── ValidationError.ts
β”‚   β”œβ”€β”€ middleware/
β”‚   β”‚   └── globalErrorHandler.ts
β”‚   └── utils/
β”‚       β”œβ”€β”€ handleRejections.ts
β”‚       └── logError.ts
β”œβ”€β”€ tests/
└── ...

πŸ’‘ Usage

Error-Cure is designed to be intuitive and easy to integrate. Here’s how you can use it in your projects:

ES Modules (import/export)

// app.ts
import express from 'express';
import { AppError, globalErrorHandler, handleUnhandledRejections } from 'error-cure';

// Handle unhandled rejections and exceptions
handleUnhandledRejections();

const app = express();

app.get('/users/:id', (req, res, next) => {
  if (req.params.id === '0') {
    return next(new AppError('Invalid user ID.', 400));
  }
  res.json({ id: req.params.id, name: 'John Doe' });
});

// Handle 404 errors
app.all('*', (req, res, next) => {
  next(new AppError(`Can't find ${req.originalUrl} on this server!`, 404));
});

// Global error handling middleware (must be last)
app.use(globalErrorHandler);

app.listen(3000, () => console.log('Server running on port 3000'));

CommonJS (require/module.exports)

// server.js
const express = require('express');
const { AppError, globalErrorHandler, handleUnhandledRejections } = require('error-cure');

// Handle unhandled rejections and exceptions
handleUnhandledRejections();

const app = express();

app.get('/users/:id', (req, res, next) => {
  if (req.params.id === '0') {
    return next(new AppError('Invalid user ID.', 400));
  }
  res.json({ id: req.params.id, name: 'John Doe' });
});

// Handle 404 errors
app.all('*', (req, res, next) => {
  next(new AppError(`Can't find ${req.originalUrl} on this server!`, 404));
});

// Global error handling middleware (must be last)
app.use(globalErrorHandler);

app.listen(3000, () => console.log('Server running on port 3000'));

βš™οΈ Configuration

The globalErrorHandler automatically adapts its response based on the NODE_ENV environment variable:

  • development: Provides detailed error information, including stack traces.
  • production: Sends minimal, user-friendly error messages.

Always set NODE_ENV=production in your production environment.

🀝 Contributing

Contributions are welcome! Please follow these steps:

  1. Fork the repository.
  2. Create a new branch (git checkout -b feature/your-feature).
  3. Make your changes and add tests.
  4. Ensure all tests pass (npm test).
  5. Commit your changes (git commit -m 'feat: Add some feature').
  6. Push to the branch (git push origin feature/your-feature).
  7. Open a Pull Request.

πŸ“„ License

This project is licensed under the MIT License. See the LICENSE.txt file for details.

πŸ”‘ Keywords

error-handling, express, node.js, middleware, error-management, custom-errors, api-errors, unhandled-rejection, uncaught-exception, logging, typescript, javascript, commonjs, esm, express-middleware, nodejs, error-logger, production-ready, developer-tools, api, backend, rest-api, error-response, json-errors

About

Error-Cure: A powerful error handling library for Node.js and Express. Provides custom error classes, global middleware, logging utilities, and tools for managing unhandled exceptions. Simplify and centralize error management for robust applications.

Topics

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published