{"id":43274571,"url":"https://github.com/dev-rashedin/express-error-toolkit","last_synced_at":"2026-02-01T16:14:06.759Z","repository":{"id":303091310,"uuid":"1014355593","full_name":"dev-rashedin/express-error-toolkit","owner":"dev-rashedin","description":"Express error handling toolkit with TypeScript support, including asyncHandler, globalErrorHandler, and notFoundHandler and more","archived":false,"fork":false,"pushed_at":"2025-10-25T08:53:47.000Z","size":612,"stargazers_count":24,"open_issues_count":1,"forks_count":3,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-10-25T10:22:08.366Z","etag":null,"topics":["dx","error-handling","express","typescript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/dev-rashedin.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null},"funding":{"github":["dev-rashedin"],"patreon":null,"open_collective":"express-error-toolkit","ko_fi":null,"tidelift":null,"community_bridge":null,"liberapay":null,"issuehunt":null,"lfx_crowdfunding":null,"polar":null,"buy_me_a_coffee":null,"thanks_dev":null,"custom":null}},"created_at":"2025-07-05T15:00:09.000Z","updated_at":"2025-10-25T08:52:01.000Z","dependencies_parsed_at":"2025-08-09T05:27:14.513Z","dependency_job_id":"3e9300fc-99ff-483b-a98a-324095b199d9","html_url":"https://github.com/dev-rashedin/express-error-toolkit","commit_stats":null,"previous_names":["dev-rashedin/express-error-toolkit"],"tags_count":8,"template":false,"template_full_name":null,"purl":"pkg:github/dev-rashedin/express-error-toolkit","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dev-rashedin%2Fexpress-error-toolkit","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dev-rashedin%2Fexpress-error-toolkit/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dev-rashedin%2Fexpress-error-toolkit/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dev-rashedin%2Fexpress-error-toolkit/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/dev-rashedin","download_url":"https://codeload.github.com/dev-rashedin/express-error-toolkit/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dev-rashedin%2Fexpress-error-toolkit/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28981893,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-01T15:35:50.179Z","status":"ssl_error","status_checked_at":"2026-02-01T15:35:38.075Z","response_time":56,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["dx","error-handling","express","typescript"],"created_at":"2026-02-01T16:14:06.020Z","updated_at":"2026-02-01T16:14:06.747Z","avatar_url":"https://github.com/dev-rashedin.png","language":"TypeScript","funding_links":["https://github.com/sponsors/dev-rashedin","https://opencollective.com/express-error-toolkit"],"categories":[],"sub_categories":[],"readme":"# express-error-toolkit\n\n[![npm version](https://img.shields.io/npm/v/express-error-toolkit)](https://www.npmjs.com/package/express-error-toolkit)\n![typescript](https://badgen.net/badge/icon/typescript?icon=typescript\u0026label)\n[![license](https://img.shields.io/npm/l/express-error-toolkit)](https://github.com/dev-rashedin/express-error-toolkit/blob/main/LICENSE)\n[![downloads](https://img.shields.io/npm/dm/express-error-toolkit)](https://www.npmjs.com/package/express-error-toolkit)\n![minified](https://badgen.net/bundlephobia/min/express-error-toolkit)\n![minified gzip](https://badgen.net/bundlephobia/minzip/express-error-toolkit)\n\n👉 [View on npm](https://www.npmjs.com/package/express-error-toolkit)\n\nA lightweight, production-ready error handling toolkit for Express.js applications — written in TypeScript with full support for both CommonJS and ESM.\n\nIf you like the project, please give the project a GitHub ⭐\n\nIt provides:\n\n- Custom error classes (`NotFoundError`, `BadRequestError`, `ValidationError`, etc.)\n- Express middleware: `globalErrorHandler`, `notFoundHandler`\n- An `asyncHandler` utility to handle async errors without boilerplate\n- A `httpError()` factory function to create custom error instances easily\n- `isCustomAPIError()` type guard for safe error type checks\n\n---\n\n## ✨ Features\n\n- ✅ Type-safe custom error classes\n- ✅ Centralized error-handling middleware\n- ✅ Async error wrapper for route handlers\n- ✅ Built-in 404 (Not Found) handler\n- ✅ Factory method for generating custom errors\n- ✅ Type guard for runtime error checking\n- ✅ Out-of-the-box support for both CJS and ESM\n\n---\n\n# 🚀 Installation Guide\n\nYou can install **express-error-toolkit** using your favorite package manager.\n\n## Using npm\n\n```bash\nnpm install express-error-toolkit\n```\n\n## Using yarn\n\n```bash\nyarn add express-error-toolkit\n```\n\n## Using pnpm\n\n```bash\npnpm add express-error-toolkit\n```\n\n\u003e ⚙️ Requires **Node.js v14 or higher**.\n\u003e ℹ️ Make sure you have `express` installed in your project, as this toolkit is built specifically to enhance Express.js error handling.\n\n---\n\n## 📁 Usage\n\n### 1. **asyncHandler**: Wrap async route handlers\n\n```ts\nimport express from 'express';\nimport { asyncHandler } from 'express-error-toolkit';\n\nconst app = express();\n\napp.get(\n  '/users/:id',\n  asyncHandler(async (req, res) =\u003e {\n    // Your async code here\n    throw new Error('Something went wrong!');\n  })\n);\n```\n\n---\n\n### 2. **Custom Errors**: Throw meaningful exceptions\n\n```ts\nimport { NotFoundError, BadRequestError } from 'express-error-toolkit';\n\napp.get('/test', (req, res) =\u003e {\n  throw new NotFoundError('User not found');\n});\n```\n\nEach custom error automatically sets the correct `statusCode` and `name`.\n\nYou can also pass optional `errorDetails` as a string, object, or leave it out:\n\n```ts\nthrow new BadRequestError('Invalid data', { field: 'email' });\nthrow new BadRequestError('Invalid input', 'Missing required field');\nthrow new BadRequestError('Generic client error');\n```\n\n---\n\n### 3. **notFoundHandler**: Catch unregistered routes\n\n```ts\nimport { notFoundHandler } from 'express-error-toolkit';\n\napp.use(notFoundHandler);\n```\n\nThis will throw a `NotFoundError` with the method and route info.\n\n---\n\n### 4. **globalErrorHandler**: Handle all errors in one place\n\n```ts\nimport { globalErrorHandler } from 'express-error-toolkit';\n\napp.use(globalErrorHandler);\n```\n\nBy default, the handler includes the stack trace and logs the error in development.\nIn production (`NODE_ENV=production`), both are automatically suppressed for safety.\n\n---\n\n### 5. 🖍️ Readable Console Logs with ANSI Colors\n\nTo enhance developer experience during debugging, this toolkit uses **ANSI escape codes** — **no external dependencies like `chalk` required** — to make console logs more readable.\n\nEach part of the error log is styled using a traffic light-inspired color scheme:\n\n- 🔴 **Error Status \u0026 Message** – Red  \n- 🟡 **Error Details** – Yellow (optional; string or object)  \n- 🟢 **Stack Trace** – Green (shown only if available and enabled)\n\n\u003e 🖼️ Example: Here's how the console might look in development mode:\n\n![Colored error output preview](./assets/console-preview-1.1.2.png)\n\n---\n\n#### ✨ Customizing the Intro Line\n\nBy default, an introductory line (*\"Even the best code breaks sometimes! Let's debug...\"*) is displayed before each error block.\n\nYou can control this with the `introLine` option:\n\n```ts\nimport { setErrorOptions } from 'express-error-toolkit';\n\n// Disable the intro line\nsetErrorOptions({\n  introLine: false\n});\n\n// Customize the intro line\nsetErrorOptions({\n  introLine: '🚨 Debugging session begins here...'\n});\n```\n\n---\n\n### 6. **Set Options Globally (Optional)**\n\nYou can configure the error handling behavior (e.g., hide stack traces and disable console logging even in development) using either:\n\n```.env\nSHOW_STACK=false\nLOG_ERROR=false\n```\n\nor directly in your code:\n\n```ts\nimport { setErrorOptions } from 'express-error-toolkit';\n\nsetErrorOptions({\n  showStack: false,\n  logError: false\n});\n```\n\nThis overrides the default behavior (based on `NODE_ENV` or `.env` file).\n\n---\n\n### 7. **httpError()**: Create generic custom errors\n\n```ts\nimport { httpError } from 'express-error-toolkit';\n\nthrow httpError('Something custom', 418);\n```\n\nYou can also pass optional `errorDetails` as a string, object, or leave it out:\n\n```ts\nthrow httpError('Expectation failed', 417,  { reason: 'The server could not meet the Expect header requirements' });\nthrow httpError('Failed Dependency', 424, 'This request relies on a previous request that failed' );\nthrow httpError('Unavailable for legal reason', 451);\n```\n\n---\n\n### 8. **isCustomAPIError()**: Type guard for checking error type\n\n```ts\nimport { isCustomAPIError } from 'express-error-toolkit';\n\nif (isCustomAPIError(err)) {\n  console.log(err.statusCode, err.message);\n  // your rest of the code \n}\n```\n\n---\n\n\n## 🔧 Custom Error Classes Available\n\n| Error Class            | Default Message         | Status Code |\n|------------------------|-------------------------|-------------|\n| `BadRequestError`      | Bad Request              | `400`       |\n| `UnauthorizedError`    | Unauthorized             | `401`       |\n| `ForbiddenError`       | Forbidden                | `403`       |\n| `NotFoundError`        | Not Found                | `404`       |\n| `ConflictError`        | Conflict                 | `409`       |\n| `ValidationError`      | Unprocessable Entity     | `422`       |\n| `TooManyRequestsError` | Too Many Requests        | `429`       |\n| `CustomAPIError`       | Internal Server Error    | `500`       |\n\n---\n\n## 📂 Directory Structure\n\n```\n├── src/\n│   ├── error/\n│   │   ├── BadRequestError.ts\n│   │   ├── NotFoundError.ts\n│   │   └── ...\n│   ├── async-handler.ts\n│   ├── global-error-handler.ts\n│   ├── http-error.ts\n│   ├── index.ts\n│   └── send-success-response.ts\n├── example/\n│   └── index.ts\n├── __tests__/\n│   └── *.test.ts\n```\n\n---\n\n## 🛠 Build \u0026 Compatibility\n\n- Fully written in TypeScript\n- Outputs:\n  - CommonJS: `dist/index.cjs`\n  - ESM: `dist/index.js`\n  - Types: `dist/index.d.ts`\n\n---\n\n## 📃 License\n\nMIT © [Rashedin Islam](https://www.rashedin.dev)\n\n---\n\n## 🙌 Acknowledgements\n\nThis project includes [`http-status-toolkit`](https://www.npmjs.com/package/http-status-toolkit), also created by me.\n\n\n## 🤝 Contribution\n\nWe welcome contributions! Please check out the [Contributing Guide](CONTRIBUTING.md).\n\n\n## Links\n\n- **GitHub:** [dev-rashedin](https://github.com/dev-rashedin)\n- **Portfolio:** [rashedin.dev](https://www.rashedin.dev)\n\n---\n\nMade with ❤️ by [Rashedin Islam](https://www.rashedin.dev)","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdev-rashedin%2Fexpress-error-toolkit","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdev-rashedin%2Fexpress-error-toolkit","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdev-rashedin%2Fexpress-error-toolkit/lists"}