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 🙏

© 2026 – Pkg Stats / Ryan Hefner

express-safe-errors

v2.0.2

Published

Lightweight Express utilites for async error handling and sending custom API responses and errors.

Readme

express-safe-errors

A lightweight, type-safe toolkit for Express.js that eliminates repetitive try...catch blocks and provides consistent API error handling.

npm version TypeScript License


Features

  • Async route wrapper to eliminate repetitive try...catch
  • Custom and standardized ApiError class with HTTP status codes
  • Ready-to-use Express error handling middleware
  • Standardized API response format
  • Fully typed with TypeScript
  • Works with Express 5+

Installation

npm install express-safe-errors

Why?

Writing Express applications often leads to repetitive code like this:

app.get("/users", async (req, res, next) => {
    try {
        const users = await User.find();

        res.json(users);
    } catch (error) {
        next(error);
    }
});

Every async route requires a try...catch, making your code harder to read.

With express-safe-errors, your controller functions become much cleaner.

import { asyncHandler } from "express-safe-errors";

app.get(
    "/users",
    asyncHandler(async (req, res) => {
        const users = await User.find();

        res.json(users);
    })
);

No more repetitive error handling.


API

asyncHandler()

Wraps asynchronous Express route handlers and automatically forwards errors to Express.

Without express-safe-errors

app.get("/users", async (req, res, next) => {
    try {
        const users = await User.find();

        res.json(users);
    } catch (error) {
        next(error);
    }
});

With express-safe-errors

import { asyncHandler } from "express-safe-errors";

app.get(
    "/users",
    asyncHandler(async (req, res) => {
        const users = await User.find();

        res.json(users);
    })
);

ApiError

A custom error class that includes an HTTP status code. Used to keep the flow of responses sent to the client consistent.

import { ApiError } from "express-safe-errors";

throw new ApiError(404, "User not found");

Example:

app.get(
    "/users/:id",
    asyncHandler(async (req, res) => {
        const user = await User.findById(req.params.id);

        if (!user) {
            throw new ApiError(404, "User not found");
        }

        res.json(user);
    })
);

errorHandler()

Creates an Express error handling middleware. Catches the errors thrown from controller functions of routes and automatically sends a response with that error object.

import { errorHandler } from "express-safe-errors";

app.use(errorHandler());

Example Response with

throw new Error(404, "User not found")

would be:

{
    "statusCode": 404,
    "message": "User not found",
    "success": false,
    "data": null
}

Important Always use this middleware at the end of all routes because Express executes middleware and routes sequentially from top to bottom.


ApiResponse

Use ApiResponse to return a consistent success response throughout your application.

import { ApiResponse } from "express-safe-errors";

res.json(
    new ApiResponse(
        200,
        {
            id: 1,
            email: [email protected] 
        },
        "User fetched successfully"
    )
);

Example Response

{
    "statusCode": 200,
    "data": {
        "id" : 1,
        "email" : "[email protected]"
    },
    "message": "User fetched successfull",
    "success": true,
}

Note the consistency in error response and normal response.


Complete Example

import express from "express";
import {
    asyncHandler,
    ApiError,
    ApiResponse,
    errorHandler
} from "express-safe-errors";

const app = express();

app.get(
    "/users/:id",
    asyncHandler(async (req, res) => {
        const { username } = req.body;

        const user = await User.findOne(username);

        if (!user) {
            throw new ApiError(404, "User not found");
        }

        return res.json(
            new ApiResponse(
                200,
                user,
                "User fetched successfully"
            )
        );
    })
);

app.use(errorHandler());

app.listen(3000);

Exported Utilities

import {
    asyncHandler,
    ApiError,
    ApiResponse,
    errorHandler
} from "express-safe-errors";

TypeScript Support

This package is written entirely in TypeScript and includes built-in type definitions.

No additional typings are required.


Requirements

  • Node.js >= 18
  • Express >= 5

Contributing

Contributions, issues, and feature requests are welcome.

If you discover a bug or have an idea for a new feature, feel free to open an issue or submit a pull request.


License

MIT © 2026