Skip to content

ali00209/throw-http-error

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

createError

A minimal utility to create and throw HTTP-style errors with validation.


🚀 Introduction

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.


📦 Installation

npm install throw-http-error

🧠 Usage

import createError from "throw-http-error"

createError(404, "User not found")

Example

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 })
})

🧰 API

createError(status: number, message: string)

Parameters

Name Type Description
status number Must be between 400–599
message string Human-readable error message

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published