{"id":18926821,"url":"https://github.com/ladjs/koa-better-error-handler","last_synced_at":"2025-08-21T19:31:12.358Z","repository":{"id":10002216,"uuid":"64058676","full_name":"ladjs/koa-better-error-handler","owner":"ladjs","description":"A better error-handler for Lad and Koa. Makes `ctx.throw` awesome (best used with koa-404-handler)","archived":false,"fork":false,"pushed_at":"2023-02-14T22:04:44.000Z","size":880,"stargazers_count":53,"open_issues_count":0,"forks_count":9,"subscribers_count":7,"default_branch":"master","last_synced_at":"2024-12-10T08:51:22.548Z","etag":null,"topics":["boom","error","error-handler","error-handling","flash","flash-messages","handler","koa","messages","node","stripe","validation"],"latest_commit_sha":null,"homepage":"https://lad.js.org","language":"JavaScript","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/ladjs.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2016-07-24T09:42:04.000Z","updated_at":"2024-07-30T16:14:06.000Z","dependencies_parsed_at":"2024-01-12T10:24:26.341Z","dependency_job_id":"1b9aa7ee-07d2-40db-a80d-00958c05d849","html_url":"https://github.com/ladjs/koa-better-error-handler","commit_stats":{"total_commits":128,"total_committers":6,"mean_commits":"21.333333333333332","dds":0.3828125,"last_synced_commit":"eb6c2cb789b05444243e884a70df86baa86d7b37"},"previous_names":[],"tags_count":51,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ladjs%2Fkoa-better-error-handler","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ladjs%2Fkoa-better-error-handler/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ladjs%2Fkoa-better-error-handler/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ladjs%2Fkoa-better-error-handler/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ladjs","download_url":"https://codeload.github.com/ladjs/koa-better-error-handler/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":230527880,"owners_count":18240052,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","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":["boom","error","error-handler","error-handling","flash","flash-messages","handler","koa","messages","node","stripe","validation"],"created_at":"2024-11-08T11:17:15.578Z","updated_at":"2024-12-20T03:10:54.548Z","avatar_url":"https://github.com/ladjs.png","language":"JavaScript","readme":"# koa-better-error-handler\n\n[![build status](https://github.com/ladjs/koa-better-error-handler/actions/workflows/ci.yml/badge.svg)](https://github.com/ladjs/koa-better-error-handler/actions/workflows/ci.yml)\n[![code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/sindresorhus/xo)\n[![styled with prettier](https://img.shields.io/badge/styled_with-prettier-ff69b4.svg)](https://github.com/prettier/prettier)\n[![made with lass](https://img.shields.io/badge/made_with-lass-95CC28.svg)](https://lass.js.org)\n[![license](https://img.shields.io/github/license/ladjs/koa-better-error-handler.svg)](LICENSE)\n\n\u003e A better error-handler for [Lad][] and [Koa][].  Makes `ctx.throw` awesome (best used with [koa-404-handler][])\n\n\n## Index\n\n* [Features](#features)\n* [Install](#install)\n* [Usage](#usage)\n  * [API](#api)\n  * [Web App](#web-app)\n* [User-Friendly Responses](#user-friendly-responses)\n* [HTML Error Lists](#html-error-lists)\n* [License](#license)\n\n\n## Features\n\n* Detects Node.js DNS errors (e.g. `ETIMEOUT` and `EBADFAMILY`) and sends 408 Client Timeout error\n* Detects Mongoose errors and sends 408 Client Timeout error\n* Detects common programmer mistakes by detecting errors of TypeError, SyntaxError, ReferenceError, RangeError, URIError, and EvalError and yields generic \"Internal Server Error\" (only applies to production mode)\n* Detects Redis errors (e.g. ioredis' MaxRetriesPerRequestError) and sends 408 Client Timeout error\n* Uses [Boom][boom] for making error messages beautiful (see [User Friendly Responses](#user-friendly-responses) below)\n* Simply a better error handler (doesn't remove all headers [like the built-in one does][gh-issue])\n* Doesn't make all status codes 500 ([like the built-in Koa error handler does][gh-500-issue])\n* Supports Flash messages and preservation of newly set session object\n* Fixes annoying redirect issue where flash messages were lost upon an error being thrown\n* Supports [HTML Error Lists](#html-error-lists) using `\u003cul\u003e` for Mongoose validation errors with more than one message\n* Makes `ctx.throw` beautiful messages (e.g. `ctx.throw(404)` will output a beautiful error object :hibiscus:)\n* Supports `text/html`, `application/json`, and `text` response types\n* Supports and recommends use of [mongoose-beautiful-unique-validation][mongoose-beautiful-unique-validation]\n\n\n## Install\n\n```bash\nnpm install --save koa-better-error-handler\n```\n\n\n## Usage\n\n\u003e You should probably be using this in combination with [koa-404-handler][] too!\n\nThe package exports a function which accepts four arguments (in order):\n\n* `cookiesKey` - defaults to `false`\n* `logger` - defaults to `console`\n* `useCtxLogger` - defaults to `true`\n* `stringify` - defaults to `fast-safe-stringify` (you can also use `JSON.stringify` or another option here if preferred)\n\nIf you pass a `cookiesKey` then support for sessions will be added. You should always set this argument's value if you are using cookies and sessions (e.g. web server).\n\nWe recommend to use [Cabin][] for your `logger` and also you should use its middleware too, as it will auto-populate `ctx.logger` for you to make context-based logs easy.\n\nNote that this package only supports `koa-generic-session`, and does not yet support `koa-session-store` (see the code in [index.js](index.js) for more insight, pull requests are welcome).\n\n### API\n\n\u003e No support for sessions, cookies, or flash messaging:\n\n```js\nconst errorHandler = require('koa-better-error-handler');\nconst Koa = require('koa');\nconst Router = require('koa-router');\nconst koa404Handler = require('koa-404-handler');\n\n// initialize our app\nconst app = new Koa();\n\n// override koa's undocumented error handler\napp.context.onerror = errorHandler();\n\n// specify that this is our api\napp.context.api = true;\n\n// use koa-404-handler\napp.use(koa404Handler);\n\n// set up some routes\nconst router = new Router();\n\n// throw an error anywhere you want!\nrouter.get('/404', ctx =\u003e ctx.throw(404));\nrouter.get('/500', ctx =\u003e ctx.throw(500));\n\n// initialize routes on the app\napp.use(router.routes());\n\n// start the server\napp.listen(3000);\nconsole.log('listening on port 3000');\n```\n\n### Web App\n\n\u003e Built-in support for sessions, cookies, and flash messaging:\n\n```js\nconst errorHandler = require('koa-better-error-handler');\nconst Koa = require('koa');\nconst redis = require('redis');\nconst RedisStore = require('koa-redis');\nconst session = require('koa-generic-session');\nconst flash = require('koa-connect-flash');\nconst convert = require('koa-convert');\nconst Router = require('koa-router');\nconst koa404Handler = require('koa-404-handler');\n\n// initialize our app\nconst app = new Koa();\n\n// define keys used for signing cookies\napp.keys = ['foo', 'bar'];\n\n// initialize redis store\nconst redisClient = redis.createClient();\nredisClient.on('connect', () =\u003e app.emit('log', 'info', 'redis connected'));\nredisClient.on('error', err =\u003e app.emit('error', err));\n\n// define our storage\nconst redisStore = new RedisStore({\n  client: redisClient\n});\n\n// add sessions to our app\nconst cookiesKey = 'lad.sid';\napp.use(\n  convert(\n    session({\n      key: cookiesKey,\n      store: redisStore\n    })\n  )\n);\n\n// add support for flash messages (e.g. `req.flash('error', 'Oops!')`)\napp.use(convert(flash()));\n\n// override koa's undocumented error handler\napp.context.onerror = errorHandler(cookiesKey);\n\n// use koa-404-handler\napp.use(koa404Handler);\n\n// set up some routes\nconst router = new Router();\n\n// throw an error anywhere you want!\nrouter.get('/404', ctx =\u003e ctx.throw(404));\nrouter.get('/500', ctx =\u003e ctx.throw(500));\n\n// initialize routes on the app\napp.use(router.routes());\n\n// start the server\napp.listen(3000);\nconsole.log('listening on port 3000');\n```\n\n\n## User-Friendly Responses\n\n\u003e Example Request:\n\n```bash\ncurl -H \"Accept: application/json\" http://localhost/some-page-does-not-exist\n```\n\n\u003e Example Response:\n\n```json\n{\n  \"statusCode\": 404,\n  \"error\": \"Not Found\",\n  \"message\":\"Not Found\"\n}\n```\n\n\n## Prevent Errors From Being Automatically Translated\n\nAs of v3.0.5, you can prevent an error from being automatically translated by setting the error property of `no_translate` to have a value of `true`:\n\n```js\nfunction middleware(ctx) {\n  const err = Boom.badRequest('Uh oh!');\n  err.no_translate = true; // \u003c----\n  ctx.throw(err);\n}\n```\n\n\n## HTML Error Lists\n\nIf you specify `app.context.api = true` or set `ctx.api = true`, and if a Mongoose validation error message occurs that has more than one message (e.g. multiple fields were invalid) – then `err.message` will be joined by a comma instead of by `\u003cli\u003e`.\n\nTherefore if you *DO* want your API error messages to return HTML formatted error lists for Mongoose validation, then set `app.context.api = false`, `ctx.api = false`, or simply make sure to not set them before using this error handler.\n\n```js\ntry {\n  // trigger manual validation\n  // (this allows us to have a 400 error code instead of 500)\n  await company.validate();\n} catch (err) {\n  ctx.throw(Boom.badRequest(err));\n}\n```\n\n\u003e With error lists:\n\n```json\n{\n  \"statusCode\": 400,\n  \"error\": \"Bad Request\",\n  \"message\": \"\u003cul class=\\\"text-left mb-0\\\"\u003e\u003cli\u003ePath `company_logo` is required.\u003c/li\u003e\u003cli\u003eGig description must be 100-300 characters.\u003c/li\u003e\u003c/ul\u003e\"\n}\n```\n\n\u003e Without error lists:\n\n```json\n{\n  \"statusCode\":400,\n  \"error\":\"Bad Request\",\n  \"message\":\"Path `company_logo` is required., Gig description must be 100-300 characters.\"\n}\n```\n\n\n## API Friendly Messages\n\nBy default if `ctx.api` is true, then [html-to-text](https://github.com/werk85/node-html-to-text) will be invoked upon the `err.message`, thus converting all the HTML markup into text format.\n\nYou can also specify a base URI in the environment variable for rendering as `process.env.ERROR_HANDLER_BASE_URL`, e.g. `ERROR_HANDLER_BASE_URL=https://example.com` (omit trailing slash), and any HTML links such as `\u003ca href=\"/foo/bar/baz\"\u003eClick here\u003c/a\u003e` will be converted to `[Click here][1]` with a `[1]` link appended of `https://example.com/foo/bar/baz`.\n\n\n## License\n\n[MIT](LICENSE) © [Nick Baugh](http://niftylettuce.com/)\n\n\n##\n\n[boom]: https://github.com/hapijs/boom\n\n[gh-issue]: https://github.com/koajs/koa/issues/571\n\n[gh-500-issue]: https://github.com/koajs/koa/blob/e4bcdecef295d7adbf5cce1bdc09adc0a24117b7/lib/context.js#L94-L140\n\n[mongoose-beautiful-unique-validation]: https://github.com/matteodelabre/mongoose-beautiful-unique-validation\n\n[lad]: https://lad.js.org\n\n[koa]: http://koajs.com/\n\n[koa-404-handler]: https://github.com/ladjs/koa-404-handler\n\n[cabin]: https://cabinjs.com\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fladjs%2Fkoa-better-error-handler","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fladjs%2Fkoa-better-error-handler","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fladjs%2Fkoa-better-error-handler/lists"}