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

imagic-errors

v2.0.1

Published

Define typed HTTP error classes and catch them as structured JSON responses

Readme

imagic-errors

HTTP error classes and catch-all middleware for Node.js servers.

Install

npm install imagic-errors

Quick Start

import { NotFoundError, catchErrors } from 'imagic-errors'

const getUser = catchErrors(async (req, res) => {
    const user = await db.find(req.params.id)
    if (!user) throw new NotFoundError('User not found')
    res.end(JSON.stringify(user))
})

API

HttpError

Base class for all HTTP errors.

new HttpError(status?: number, message?: string, details?: any)

| Parameter | Type | Default | Description | |-----------|------|---------|-------------| | status | number | 500 | HTTP status code | | message | string | 'HTTP Error' | Human-readable message | | details | any | null | Additional data attached to the error |

Properties:

| Property | Type | Description | |----------|------|-------------| | .name | string | Constructor name (e.g. 'NotFoundError') | | .status | number | HTTP status code | | .message | string | Error message | | .details | any \| null | Extra context | | .stack | string | Stack trace |

Methods:

error.toJSON(): { code: string, status: number, message: string, details?: any }

Returns a plain object ready for JSON.stringify. The details field is omitted when it is null.


HTTP Error Subclasses

All subclasses extend HttpError and accept (message?, details?).

| Class | Status | Default message | |-------|--------|-----------------| | BadRequestError | 400 | 'Bad Request' | | UnauthorizedError | 401 | 'Unauthorized' | | ForbiddenError | 403 | 'Forbidden' | | NotFoundError | 404 | 'Not Found' | | MethodNotAllowedError | 405 | 'Method Not Allowed' | | ConflictError | 409 | 'Conflict' | | UnprocessableEntityError | 422 | 'Unprocessable Entity' | | TooManyRequestsError | 429 | 'Too Many Requests' | | InternalServerError | 500 | 'Internal Server Error' | | BadGatewayError | 502 | 'Bad Gateway' | | ServiceUnavailableError | 503 | 'Service Unavailable' |

new NotFoundError(message?: string, details?: any)
// .status === 404, .name === 'NotFoundError'

Each subclass sets .status automatically and sets .name to the class name.


isHttpError(err, status?)

isHttpError(err: unknown, status?: number): boolean

Returns true if err is an instance of HttpError. When status is provided, also checks that err.status === status.

isHttpError(new NotFoundError())        // true
isHttpError(new NotFoundError(), 404)   // true
isHttpError(new NotFoundError(), 400)   // false
isHttpError(new Error('plain'))         // false

catchErrors(handler)

catchErrors(
    handler: (req: IncomingMessage, res: ServerResponse) => Promise<void>
): (req: IncomingMessage, res: ServerResponse) => Promise<void>

Wraps an async route handler. On error:

  • HttpError → responds with err.status and err.toJSON() as JSON body.
  • Any other error → responds with 500 and a generic JSON body.

Sets Content-Type: application/json in both error cases.

const wrapped = catchErrors(async (req, res) => {
    throw new ForbiddenError('Access denied')
})
// responds: 403 { "data": null, "error": { "code": "ForbiddenError", "status": 403, "message": "Access denied" } }

Error Handling

| Situation | Result | |-----------|--------| | Handler throws HttpError | err.status response with err.toJSON() JSON body | | Handler throws any other Error | 500 response with generic InternalServerError JSON body | | Handler resolves normally | No interference — response is handled by the route handler |

catchErrors never re-throws. All errors are converted to JSON HTTP responses.

Examples

See examples/basic.js for a working demo with a plain node:http server.

node examples/basic.js

License

MIT