1.0.3 โ€ข Published 5 months ago

express-universal-error-handler v1.0.3

Weekly downloads
-
License
MIT
Repository
-
Last release
5 months ago

express-universal-error-handler ๐Ÿ›ก๏ธ

A universal error handler middleware for Express.js that handles synchronous, asynchronous, and custom errors gracefully.


๐Ÿ“ฆ Installation

npm install express-universal-error-handler

๐Ÿš€ Usage

const express = require('express');
const { errorHandler, CustomError } = require('express-universal-error-handler');
const asyncWrapper = require('express-universal-error-handler/asyncWrapper');

const app = express();

// Example Sync Route
app.get('/sync-error', () => {
    throw new Error('Sync Error Example');
});

// Example Async Route
app.get('/async-error', asyncWrapper(async () => {
    throw new Error('Async Error Example');
}));

// Example Custom Error Route
app.get('/custom-error', () => {
    throw new CustomError('Custom Error Example', 400);
});

// Use the error handler middleware
app.use(errorHandler());

// Start Server
app.listen(3000, () => console.log('Server running on http://localhost:3000'));

โœ… Features

  • ๐Ÿ“ฆ Simple plug-and-play Express middleware
  • ๐Ÿ’ช Handles sync, async, and custom errors
  • ๐Ÿ“Š Structured JSON error responses
  • ๐Ÿš€ Lightweight and fast

๐Ÿงช Testing

Run tests using Jest:

npm test

๐Ÿ›ก๏ธ API

asyncWrapper(fn)

Wraps async functions to catch errors automatically and pass them to the error handler.

errorHandler(options)

Handles all types of errors and returns consistent JSON responses. โ€ข logErrors (boolean) โ€“ Enable logging (default: true) โ€ข hideStackTrace (boolean) โ€“ Hide error stack traces (default: based on environment)

CustomError(message, statusCode)

Create custom application errors with status codes.

๐Ÿ’ก Examples

Custom Error Example:

app.get('/custom-error', () => {
    throw new CustomError('This is a custom error', 400);
});

Async Error Example::

app.get('/async-error', asyncWrapper(async () => {
    throw new Error('Async error occurred');
}));

Structured Error Response Example:

{
    "status": "error",
    "message": "Async error occurred",
    "code": 500
}

๐Ÿงฐ Requirements

  • Express.js 4+
  • Node.js 16+
1.0.3

5 months ago

1.0.2

5 months ago

1.0.1

5 months ago

1.0.0

5 months ago