# express-error-toolkit — the One NPM Package to Handle All Express Errors

As a full-stack developer, I’ve spent countless hours building robust backend applications with Express.js. While Express is lightweight and unopinionated — exactly what makes it great — error handling has always been repetitive and tedious.

I was tired of copy-pasting the same boilerplate across projects:

- ✅ Writing **`notFoundHandler`** manually
- ✅ Writing **`globalErrorHandler`** for every single project
- ✅ Wrapping every async function in a try-catch or **`asyncHandler`**
- ✅ Creating **`CustomApiError`**, **`NotFoundError`**, **`BadrequestError`** and other custom errors.
- ✅ Installing separate libraries like **`chalk`** just to make my logs more readable

Even after using popular libraries like `express-async-errors` or `async-error-handler`, I still had to manually wire up custom errors and error-handling middleware. And none of them improved the developer experience in the terminal.

So, I built  - 🔗 [express-error-toolkit](https://www.npmjs.com/package/express-error-toolkit)   — the one package to handle all Express errors.

---

## 🧰 What's Included?

This package provides everything you need to handle errors in a production-grade Express app:

- ✅ Type-safe custom error classes (**`NotFoundError`**, **`BadRequestError`**, etc.)
- ✅ Drop-in middleware: **`globalErrorHandler`**, **`notFoundHandler`**
- ✅ A clean **`asyncHandler`** utility
- ✅ A **`httpError()`** function for custom one-liners
- ✅ Colorful and readable console logs — no need for **`chalk`** or similar
- ✅ Flexible **`.env`** or programmatic configuration
- ✅ Built-in support for CommonJS and ESM
- ✅ Designed with DX in mind




![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/js7lgfffzr9q6kvud1jw.png)

---

## 🏗 Build Process

The package is written entirely in **TypeScript** and built with:

- [tsup](https://github.com/egoist/tsup) — lightning-fast bundler
- [http-status-toolkit](https://www.npmjs.com/package/http-status-toolkit) — my own utility, to handle http-status-codes in more human readable way
- **ANSI escape codes** — to create colorful terminal output (no dependencies required)

The idea was to bundle everything in a single utility that you can drop into any Express project, and instantly get a polished, configurable, DX-optimized error system.

---

## ⚡ Installation

```bash
npm install express-error-toolkit
```



> ℹ️ Requires Node.js version `>=14`
 
> Make sure you have **`express`** installed in your project.

---

## 📦 Usage Examples

### 1. **Wrap async route handlers**



```ts
import { asyncHandler } from 'express-error-toolkit';

app.get('/users/:id', asyncHandler(async (req, res) => 
{throw new Error('User not found');   }) );
```

---

### 2. **Use custom errors**


```ts
import { NotFoundError } from 'express-error-toolkit';  

app.get('/user/:id', (req, res) => 
{throw new NotFoundError('User not found'); });
```

---

### 3. **Catch unregistered routes**


```ts
import { notFoundHandler } from 'express-error-toolkit';

app.use(notFoundHandler);
```

---

### 4. **Global error handler**


```ts
import { globalErrorHandler } from 'express-error-toolkit';  

app.use(globalErrorHandler);
```

By default, it includes stack trace and logs the error, but removes both when **`NODE_ENV=production`**.

---

## 🧪 Console Output — Traffic Light Theme

To make debugging more intuitive, `express-error-toolkit` uses ANSI escape codes to show:

- 🔴 **Error Message** in **bold red**
    
- 🟡 **Error Details** in **bold yellow**
    
- 🟢 **Stack Trace** in **dim green**, line-by-line


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mpmwti0bsvdnkilsiy9p.png)
    

### 📸 Console Preview:

  
<sub>Colors are styled without external libraries — just pure ANSI codes</sub>

---

## 🛠️ Optional Configuration

### 5. **Set Options Globally (Optional)**

You can configure the error handling behavior (e.g., hide stack traces, configuring intro line in console, and disable console logging even in development) using either:

#### ✅ Via && `.env`**:

**`SHOW_STACK=false LOG_ERROR=false`**

#### ✅ Or directly in your code:

```ts
import { setErrorOptions } from 'express-error-toolkit'; 
 setErrorOptions({showStack: false, logError: false, introLine: false });
```

This overrides the default behavior (based on `NODE_ENV` or `.env` file).

---

## 📚 Utility Helpers


```ts
import { httpError, StatusCodes } from 'express-error-toolkit';
  
throw httpError('Something broke!', StatusCodes.BAD_REQUEST);
```


```ts
import { isCustomAPIError } from 'express-error-toolkit';  

if (isCustomAPIError(err)) {   console.log(err.statusCode, err.message); }
```

---

## 🔥 Why It Improves Developer Experience

- 🧼 Cleaner, centralized error handling
    
- ⌛ Saves hours of repetitive setup
    
- 🧠 Human-readable, styled error logs
    
- 🚫 No unnecessary dependencies (like `chalk`)
    
- ⚙️ Easily configurable — no lock-in, no magic
    

---

## 📁 Output

The build generates:

- `dist/index.cjs.js` — CommonJS
    
- `dist/index.esm.js` — ESM
    
- `dist/index.d.ts` — TypeScript types
    

---

## 💼 Ideal For

- Full-stack teams building REST APIs
    
- Developers who care about clean DX
    
- Production-ready Express.js apps
    
- Anyone tired of writing error handlers over and over


---

## 🧭 Want to Explore?

- 🔗 [View on npm](https://www.npmjs.com/package/express-error-toolkit)  
- 💻 [View source on GitHub](https://github.com/dev-rashedin/express-error-toolkit)  
- 🌐 [Visit my portfolio](https://www.rashedin.dev)
   

---

## 📃 License

MIT © [Rashedin Islam](https://www.rashedin.dev)

---

## 🙌 Acknowledgements

- [http-status-toolkit](https://www.npmjs.com/package/http-status-toolkit) 
    
- ANSI escape codes — for stylish logging without bloat
    

---

Built with ❤️ and TypeScript by [Rashedin Islam](https://www.rashedin.dev)  
If you find it useful, consider giving it a ⭐ on GitHub.
