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

@x-titan/koa-error-handler

v0.3.0

Published

A lightweight error-handling middleware for Koa with customizable formatters.

Downloads

249

Readme

@x-titan/koa-error-handler

🧩 A minimal, composable error handler middleware for Koa, designed for pure REST APIs.

It provides a small, flexible structure for handling errors — without hiding logic from developers.
You control how errors are prepared and formatted, while the middleware handles the basic flow.


✨ Features

  • ⚙️ Minimal: no dependencies beyond Koa
  • 🧽 Flexible: developer controls how errors are formatted
  • 🔒 Safe: prevents double responses
  • 🤓 Developer-friendly with optional debug logging
  • 🌐 REST-only (JSON output)

📦 Installation

npm install @x-titan/koa-error-handler

🚀 Usage

import Koa from "koa"
import createHttpError, { type HttpError } from "http-errors"
import error, { ErrorEvent } from "@x-titan/koa-error-handler"

const app = new Koa()

app.use(error({
  prepare(error) {
    // Normalize to HttpError
    return createHttpError(
      error.status || 500,
      error.message || "Internal Server Error"
    )
  },

  onerror(event: ErrorEvent<HttpError>) {
    const err = event.error as HttpError

    // Format final JSON response
    event.body = {
      success: false,
      message: err.expose ? err.message : "Internal Server Error",
      status: err.status,
      timestamp: new Date().toISOString(),
    }

    event.status = err.status
  }
}))

app.use(async ctx => {
  ctx.throw(400, "Invalid input")
})

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

⚙️ API

error(options?: ErrorHandlerOptions | ErrorEventListener)

Creates a Koa middleware for centralized error handling.

Options

| Option | Type | Description | |--------|------|-------------| | prepare | (error: any) => any | Optional. Normalize or wrap any thrown error before handling error event. | | onerror | (event: ErrorEvent) => void | Required. Define how the final JSON response should look. | | finalize | (event: ErrorEvent) => void | Optional. Mutate the response before sending (e.g., for logging). | | debug | boolean | Optional. Logs caught errors to console when true. Defaults to process.env.NODE_ENV === "development". |


ErrorEvent

Each onerror receives an ErrorEvent object:

type ErrorEvent<Err = any> = {
  error: Err
  status: number
  body: any
  type: string
  meta: {
    accepts: string[] | string | false
    method: string
    path: string
  }
}

💡 Design Philosophy

  • This package does not automatically normalize errors.
    → Developers decide how to shape their own responses.
  • No magic defaults, no HTML responses, no stack traces unless you add them.

🧠 Example: Production vs Development

import error from "@x-titan/koa-error-handler"
import createHttpError from "http-errors"

app.use(error({
  prepare(error) {
    return createHttpError(error.status || 500, error.message)
  },
  onerror(event) {
    const err = event.error
    const isDev = process.env.NODE_ENV === "development"

    event.body = {
      success: false,
      message: err.expose ? err.message : "Internal Server Error",
      ...(isDev && { stack: err.stack }),
    }

    event.status = err.status
  }
}))

🧺 Default Behavior

If no onerror is provided:

{
  "error": "Internal Server Error"
}

📝 License

MIT © 2025 Aset Telmanov