npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

express-error-catcher

v1.0.2

Published

async error handler

Downloads

262,507

Readme

express-error-catcher

express-error-catcher is a robust npm package engineered to streamline error handling in Node.js Express applications. It provides an elegant solution for managing async/await errors, reducing boilerplate code, and enhancing the maintainability of your applications.

Key Features

  • Automated Error Handling: Effortlessly catch and handle errors in asynchronous route handlers, allowing for cleaner and more concise code.
  • Customizable Middleware: Easily configure default error messages, status codes, and logging preferences to suit your development and production environments.
  • Multiple Logging Formats: Choose between detailed development logs and minimal production logs to meet your specific needs.
  • Improved Code Readability: Eliminate redundant try-catch blocks, making your codebase more readable and easier to maintain.

Installation

Integrating express-error-catcher into your project is straightforward. Use the following npm command to install the package:

npm install express-error-catcher

Usage Overview

To leverage express-error-catcher in your Express application, follow these steps:

Step 1: Import the Package

Begin by importing the necessary functions and middleware from the express-error-catcher package.

import express from "express";
import { asyncErrorHandler, error, Response, Error } from "express-error-catcher";

Step 2: Configure Error Handling Middleware

Apply the error-handling middleware with optional configuration parameters to customize its behavior.

const app = express();

app.use(error({
  defaultErrorMessage: "Internal server error", // Sets a default error message for uncaught errors.
  defaultStatusCode: 500, // Defines the default HTTP status code for errors.
  log: "dev" // Chooses the logging format: "dev" for detailed logs, "prod" for concise logs.
}));

Step 3: Define Route Handlers

Use the asyncErrorHandler function to wrap your asynchronous route handlers. This ensures that any errors are automatically caught and passed to the error-handling middleware.

app.get(
  "/name",
  asyncErrorHandler((req, res) => {
    // Intentionally throwing an error
    throw Error("Error while retrieving name", 500);

    // Returning a successful response
    return Response("Successfully retrieved name", { name: "Daisy" }, 200);
  })
);

Step 4: Start the Express Server

Finally, start your Express server as usual:

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

Detailed Configuration Options

The error middleware provides a range of configuration options to tailor error handling to your application’s requirements.

  • defaultErrorMessage: A string specifying the default message to return when an error is unhandled.
  • defaultStatusCode: An integer representing the default HTTP status code to use when responding to unhandled errors.
  • log: A string determining the log format. Options include:
    • "dev": Detailed log output for development, including error messages and file paths.
    • "pretty": A more readable format compared to dev, with enhanced formatting for better human readability. Example.
    • "production": Simplified log output for production environments, focusing on error messages only.

Logging Formats

Development (dev)

In development mode, express-error-catcher provides detailed logs that include the error message, file path, and line number, presented in a table format for easy reading:

<------------------------------->
ERROR => Internal Server Error
FILE => /path/to/file.js:16:11
<------------------------------->

Pretty (pretty)

In development mode, express-error-catcher offers detailed logs in a table format that includes the error message and file path. This format enhances readability and helps quickly identify issues:

┌─────────┬─────────────────────────┬────────────────────────────────┐
│ (index) │ Message                 │ File                           │
├─────────┼─────────────────────────┼────────────────────────────────┤
│ 0       │ 'Internal Server Error' │ '/path/to/file.js:16:11'       │
└─────────┴─────────────────────────┴────────────────────────────────┘

Production (production)

In production mode, logs are minimized to reduce noise and focus on essential information:

<------------------------------->
ERROR => Internal Server Error
<------------------------------->

Advanced Use Cases

Handling Custom Errors

express-error-catcher allows you to define and handle custom errors with specific messages and status codes, providing fine-grained control over error management.

throw Error("Custom error message", 400);

Response Format

Success Response

When an operation completes successfully, the response is structured as follows:

return new Response("Success.", { data: "Welcome daisy.." }, 200);

The corresponding JSON output will be:

{
  "code": 200,
  "success": true,
  "status": "OK",
  "message": "Success.",
  "data": "Welcome daisy.."
}

Error Response

If an error occurs during processing, an error is thrown with the following structure:

throw new Error("Daisy already exists.", 400);

The corresponding JSON output will be:

{
  "success": false,
  "code": 400,
  "status": "Bad Request",
  "message": "Daisy already exists."
}

Error Response with Additional Data

You can also include additional data in the error response for more context:

throw new Error("Daisy already exists.", 400, { details: "Validation failed" });
{
  "success": false,
  "code": 400,
  "status": "Bad Request",
  "message": "Daisy already exists.",
  "data": {
    "details": "Validation failed"
  }
}

Integrating with Other Middleware

The package is designed to integrate seamlessly with other Express middleware, allowing you to create a cohesive error-handling strategy across your application.