{"id":19165669,"url":"https://github.com/loopbackio/strong-error-handler","last_synced_at":"2025-05-16T16:10:11.324Z","repository":{"id":36972497,"uuid":"50195364","full_name":"loopbackio/strong-error-handler","owner":"loopbackio","description":"Error handler for use in development (debug) and production environments.","archived":false,"fork":false,"pushed_at":"2025-05-08T13:00:29.000Z","size":884,"stargazers_count":38,"open_issues_count":8,"forks_count":35,"subscribers_count":26,"default_branch":"master","last_synced_at":"2025-05-08T14:19:53.437Z","etag":null,"topics":["error-handler","express","hacktoberfest","loopback","nodejs"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/loopbackio.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGES.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.md","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":"CODEOWNERS","security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2016-01-22T17:08:22.000Z","updated_at":"2025-05-08T13:00:05.000Z","dependencies_parsed_at":"2023-10-11T02:45:22.268Z","dependency_job_id":"20bdd984-a64c-4236-a88a-77cdb9c563bd","html_url":"https://github.com/loopbackio/strong-error-handler","commit_stats":{"total_commits":475,"total_committers":29,"mean_commits":"16.379310344827587","dds":"0.30105263157894735","last_synced_commit":"276b701c3cf8a7372219b735e7e9155b1f4e018c"},"previous_names":["strongloop/strong-error-handler"],"tags_count":46,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/loopbackio%2Fstrong-error-handler","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/loopbackio%2Fstrong-error-handler/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/loopbackio%2Fstrong-error-handler/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/loopbackio%2Fstrong-error-handler/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/loopbackio","download_url":"https://codeload.github.com/loopbackio/strong-error-handler/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254564127,"owners_count":22092122,"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":["error-handler","express","hacktoberfest","loopback","nodejs"],"created_at":"2024-11-09T09:28:56.495Z","updated_at":"2025-05-16T16:10:11.304Z","avatar_url":"https://github.com/loopbackio.png","language":"JavaScript","readme":"# strong-error-handler\n\n[![OpenSSF Best Practices](https://www.bestpractices.dev/projects/8058/badge)](https://www.bestpractices.dev/projects/8058)\n[![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/loopbackio/strong-error-handler/badge)](https://securityscorecards.dev/viewer/?uri=github.com/loopbackio/strong-error-handler)\n[![Continuous Integration](https://github.com/loopbackio/strong-error-handler/actions/workflows/continuous-integration.yml/badge.svg)](https://github.com/loopbackio/strong-error-handler/actions/workflows/continuous-integration.yml)\n[![CodeQL](https://github.com/loopbackio/strong-error-handler/actions/workflows/codeql-analysis.yml/badge.svg)](https://github.com/loopbackio/strong-error-handler/actions/workflows/codeql-analysis.yml)\n\nThis package is an error handler for use in both development (debug) and production environments.\n\nIn production mode, `strong-error-handler` omits details from error responses to prevent leaking sensitive information:\n\n- For 5xx errors, the output contains only the status code and the status name from the HTTP specification.\n- For 4xx errors, the output contains the full error message (`error.message`) and the contents of the `details`\n  property (`error.details`) that `ValidationError` typically uses to provide machine-readable details\n  about validation problems. It also includes `error.code` to allow a machine-readable error code to be passed\n  through which could be used, for example, for translation.\n\nIn debug mode, `strong-error-handler` returns full error stack traces and internal details of any error objects to the client in the HTTP responses.\n\n## Supported versions\n\nThis module adopts the [Module Long Term Support (LTS)](http://github.com/CloudNativeJS/ModuleLTS) policy, with the following End Of Life (EOL) dates:\n\n| Version    | Status          | Published | EOL                  |\n| ---------- | --------------- | --------- | -------------------- |\n| 4.x        | Current         | Oct 2020  | Apr 2023 _(minimum)_ |\n| 3.x        | Active LTS      | Jun 2018  | Dec 2022             |\n| 2.x        | End-of-life     | Mar 2017  | Oct 2020             |\n\nLearn more about our LTS plan in the [LoopBack documentation](http://loopback.io/doc/en/contrib/Long-term-support.html).\n\n## Installation\n\n```bash\n$ npm install --save strong-error-handler\n```\n\n## Use\n\nIn an Express-based application:\n\n```js\nvar express = require('express');\nvar errorHandler = require('strong-error-handler');\n\nvar app = express();\n// setup your routes\n// `options` are set to default values. For more info, see `options` below.\n// app.use(errorHandler({ /* options, see below */ }));\napp.use(errorHandler({\n  debug: app.get('env') === 'development',\n  log: true,\n}));\n\napp.listen(3000);\n```\n\nThe module also exports `writeErrorToResponse`, a non-middleware flavor of the\nerror handler:\n\n```js\nconst http = require('http');\nconst writeErrorToResponse = require('strong-error-handler')\n  .writeErrorToResponse;\nconst errHandlingOptions = {debug: process.env.NODE_ENV === 'development'}\n\nhttp\n  .createServer((req, res) =\u003e {\n    if (errShouldBeThrown) {\n      writeErrorToResponse(\n        new Error('something went wrong'),\n        req,\n        res,\n        errHandlingOptions,\n      );\n    }\n  })\n  .listen(3000);\n```\n\nIn LoopBack applications, add the following entry to `server/middleware.json`:\n\n```json\n{\n  \"final:after\": {\n    \"strong-error-handler\": {\n      \"params\": {\n         \"debug\": false,\n         \"log\": true\n       }\n    }\n  }\n}\n```\n\nIn general, `strong-error-handler` must be the last middleware function registered.\n\nThe above configuration will log errors to the server console, but not return stack traces in HTTP responses.\nFor details on configuration options, see below.\n\n### Response format and content type\n\nThe `strong-error-handler` package supports JSON, HTML and XML responses:\n\n- When the object is a standard Error object, it returns the string provided by the stack property in HTML/text\n  responses.\n- When the object is a non-Error object, it returns the result of `util.inspect` in HTML/text responses.\n- For JSON responses, the result is an object with all enumerable properties from the object in the response.\n\nThe content type of the response depends on the request's `Accepts` header.\n\n-  For Accepts header `json` or `application/json`, the response content type is JSON.\n-  For Accepts header `html` or `text/html`, the response content type is HTML.\n-  For Accepts header `xml` or `text/xml`, the response content type is XML.\n\n*There are plans to support other formats such as Plain-text.*\n\n## Options\n\n| Option               | Type                      | Default   | Description                                                                                                                                                                                                                                                                                                                                               |\n| -------------------- | ------------------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| debug                | Boolean\u0026nbsp;\u0026nbsp;\u0026nbsp; | `false`   | If `true`, HTTP responses include all error properties, including sensitive data such as file paths, URLs and stack traces. See [Example output](#example) below.                                                                                                                                                                                         |\n| log                  | Boolean                   | `true`    | If `true`, all errors are printed via `console.error`, including an array of fields (custom error properties) that are safe to include in response messages (both 4xx and 5xx). \u003cbr/\u003e If `false`, sends only the error back in the response.                                                                                                              |\n| safeFields           | [String]                  | `[]`      | Specifies property names on errors that are allowed to be passed through in 4xx and 5xx responses. See [Safe error fields](#safe-error-fields) below.                                                                                                                                                                                                     |\n| defaultType          | String                    | `\"json\"`  | Specifies the default response content type to use when the client does not provide any Accepts header.                                                                                                                                                                                                                                                   |\n| rootProperty         | String or false           | `\"error\"` | Specifies the root property name for json or xml. If the value is set to `false`, no wrapper will be added to the json object. The false value is ignored by XML as a root element is always required.                                                                                                                                                    |\n| negotiateContentType | Boolean                   | true      | Negotiate the response content type via Accepts request header. When disabled, strong-error-handler will always use the default content type when producing responses. Disabling content type negotiation is useful if you want to see JSON-formatted error responses in browsers, because browsers usually prefer HTML and XML over other content types. |\n\n### Customizing log format\n\n**Express**\n\nTo use a different log format, add your own custom error-handling middleware then disable `errorHandler.log`.\nFor example, in an Express application:\n\n```js\napp.use(myErrorLogger());\napp.use(errorHandler({log: false}));\n```\n\nIn general, add `strong-error-handler` as the last middleware function, just before calling `app.listen()`.\n\n**LoopBack**\n\nFor LoopBack applications, put custom error-logging middleware in a separate file; for example, `server/middleware/error-logger.js`:\n\n```\nmodule.exports = function(options) {\n  return function logError(err, req, res, next) {\n    console.log('unhandled error' ,err);\n    next(err);\n  };\n};\n```\n\nThen in `server/middleware.json`, specify your custom error logging function as follows:\n\n```\n{\n  // ...\n  \"final:after\": {\n    \"./middleware/error-logger\": {},\n    \"strong-error-handler\": {\n      \"params\": {\n        \"log\": false\n      }\n    }\n}\n```\n\nThe default `middleware.development.json` file explicitly enables logging in strong-error-handler params, so you will need to change that file too.\n\n### Safe error fields\n\nBy default, `strong-error-handler` will only pass through the `name`, `message` and `details` properties of an error. Additional error\nproperties may be allowed through on 4xx and 5xx status code errors using the `safeFields` option to pass in an array of safe field names:\n\n```\n{\n  \"final:after\": {\n    \"strong-error-handler\": {\n      \"params\": {\n        \"safeFields\": [\"errorCode\"]\n      }\n    }\n}\n```\n\nUsing the above configuration, an error containing an `errorCode` property will produce the following response:\n\n```\n{\n  \"error\": {\n    \"statusCode\": 500,\n    \"message\": \"Internal Server Error\",\n    \"errorCode\": \"INTERNAL_SERVER_ERROR\"\n  }\n}\n```\n\n## Migration from old LoopBack error handler\n\nNOTE: This is only required for applications scaffolded with old versions of the `slc loopback` tool.\n\nTo migrate a LoopBack 2.x application to use `strong-error-handler`:\n\n1. In `package.json` dependencies, remove `\"errorhandler\": \"^x.x.x”,`\n1. Install the new error handler by entering the command:\n    \u003cpre\u003enpm install --save strong-error-handler\u003c/pre\u003e\n1. In `server/config.json`, remove:\n    \u003cpre\u003e\n    \"remoting\": {\n      ...\n      \"errorHandler\": {\n        \"disableStackTrace\": false\n      }\u003c/pre\u003e\n    and replace it with:\n    \u003cpre\u003e\n    \"remoting\": {\n      ...,\n      \"rest\": {\n        \"handleErrors\": false\n      }\u003c/pre\u003e\n1. In `server/middleware.json`, remove:\n    \u003cpre\u003e\n    \"final:after\": {\n      \"loopback#errorHandler\": {}\n    }\u003c/pre\u003e\n    and replace it with:\n    \u003cpre\u003e\n    \"final:after\": {\n      \"strong-error-handler\": {}\n    }\u003c/pre\u003e\n1. Delete `server/middleware.production.json`.\n1. Create `server/middleware.development.json` containing:\n    \u003cpre\u003e\n    \"final:after\": {\n      \"strong-error-handler\": {\n        \"params\": {\n          \"debug\": true,\n          \"log\": true\n        }\n      }\n    }\n\u003c/pre\u003e\n\nFor more information, see\n[Migrating apps to LoopBack 3.0](http://loopback.io/doc/en/lb3/Migrating-to-3.0.html#update-use-of-rest-error-handler).\n\n## Example\n\n5xx error generated when `debug: false` :\n\n```\n{ error: { statusCode: 500, message: 'Internal Server Error' } }\n```\n\nThe same error generated when `debug: true` :\n\n```\n{ error:\n  { statusCode: 500,\n  name: 'Error',\n  message: 'a test error message',\n  stack: 'Error: a test error message\n  at Context.\u003canonymous\u003e (User/strong-error-handler/test/handler.test.js:220:21)\n  at callFnAsync (User/strong-error-handler/node_modules/mocha/lib/runnable.js:349:8)\n  at Test.Runnable.run (User/strong-error-handler/node_modules/mocha/lib/runnable.js:301:7)\n  at Runner.runTest (User/strong-error-handler/node_modules/mocha/lib/runner.js:422:10)\n  at User/strong-error-handler/node_modules/mocha/lib/runner.js:528:12\n  at next (User/strong-error-handler/node_modules/mocha/lib/runner.js:342:14)\n  at User/strong-error-handler/node_modules/mocha/lib/runner.js:352:7\n  at next (User/strong-error-handler/node_modules/mocha/lib/runner.js:284:14)\n  at Immediate._onImmediate (User/strong-error-handler/node_modules/mocha/lib/runner.js:320:5)\n  at tryOnImmediate (timers.js:543:15)\n  at processImmediate [as _immediateCallback] (timers.js:523:5)' }}\n```\n\n4xx error generated when `debug: false` :\n\n```\n{ error:\n  { statusCode: 422,\n  name: 'Unprocessable Entity',\n  message: 'Missing required fields',\n  code: 'MISSING_REQUIRED_FIELDS' }}\n```\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Floopbackio%2Fstrong-error-handler","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Floopbackio%2Fstrong-error-handler","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Floopbackio%2Fstrong-error-handler/lists"}