A minimal utility to create and throw HTTP-style errors with validation.
createError is a tiny utility for creating and throwing HTTP-style errors in Node.js applications. It ensures that only valid HTTP error codes (400–599) are used, making your error handling more consistent and secure.
Useful in frameworks like Express, Koa, or any async/await setup.
npm install throw-http-errorimport createError from "throw-http-error"
createError(404, "User not found")import express from "express"
import createError from "throw-http-error"
const app = express()
app.get("/dashboard", (req, res, next) => {
try {
const loggedIn = false
if (!loggedIn) createError(401, "Unauthorized")
res.send("Dashboard")
} catch (err) {
next(err)
}
})
app.use((err, req, res, next) => {
res.status(err.status || 500).json({ message: err.message })
})createError(status: number, message: string)| Name | Type | Description |
|---|---|---|
status |
number |
Must be between 400–599 |
message |
string |
Human-readable error message |