{"id":14676803,"url":"https://github.com/mamsoudi/merror","last_synced_at":"2025-04-10T18:20:42.264Z","repository":{"id":98883639,"uuid":"115876521","full_name":"mamsoudi/merror","owner":"mamsoudi","description":"A REST-friendly Express Middleware for HTTP error handling","archived":false,"fork":false,"pushed_at":"2022-12-07T11:14:32.000Z","size":398,"stargazers_count":29,"open_issues_count":5,"forks_count":0,"subscribers_count":1,"default_branch":"develop","last_synced_at":"2024-04-25T22:02:10.236Z","etag":null,"topics":["error-handling","error-messages","express","express-middleware","expressjs","nodejs"],"latest_commit_sha":null,"homepage":"http://masoudmirzaei.ir/merror","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/mamsoudi.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":"2017-12-31T17:24:31.000Z","updated_at":"2024-04-20T05:23:34.000Z","dependencies_parsed_at":"2023-04-11T17:17:34.229Z","dependency_job_id":null,"html_url":"https://github.com/mamsoudi/merror","commit_stats":{"total_commits":10,"total_committers":2,"mean_commits":5.0,"dds":0.5,"last_synced_commit":"26ed44765cd5036cd74c63be56a5a687fb54a0e9"},"previous_names":[],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mamsoudi%2Fmerror","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mamsoudi%2Fmerror/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mamsoudi%2Fmerror/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mamsoudi%2Fmerror/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mamsoudi","download_url":"https://codeload.github.com/mamsoudi/merror/tar.gz/refs/heads/develop","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248270469,"owners_count":21075794,"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-handling","error-messages","express","express-middleware","expressjs","nodejs"],"created_at":"2024-09-12T09:00:56.451Z","updated_at":"2025-04-10T18:20:42.234Z","avatar_url":"https://github.com/mamsoudi.png","language":"TypeScript","funding_links":[],"categories":["Middleware"],"sub_categories":[],"readme":"![Merror](https://github.com/mamsoudi/merror/raw/master/resources/logo-150.png \"Merror\")\n\n[![Build Status](https://travis-ci.org/mamsoudi/merror.svg?branch=master)](https://travis-ci.org/mamsoudi/merror) [![bitHound Dependencies](https://www.bithound.io/github/mamsoudi/merror/badges/dependencies.svg)](https://www.bithound.io/github/mamsoudi/merror/master/dependencies/npm) [![bitHound Dev Dependencies](https://www.bithound.io/github/mamsoudi/merror/badges/devDependencies.svg)](https://www.bithound.io/github/mamsoudi/merror/master/dependencies/npm) [![bitHound Code](https://www.bithound.io/github/mamsoudi/merror/badges/code.svg)](https://www.bithound.io/github/mamsoudi/merror) [![bitHound Overall Score](https://www.bithound.io/github/mamsoudi/merror/badges/score.svg)](https://www.bithound.io/github/mamsoudi/merror)\n\n# Merror \n\nDeveloping REST APIs with Express, I was always looking for a clean way to send HTTP error responses along with the data I wanted, not only to allow clients to know which error has happened but to provide the information I wanted.\n\nExpress allows you to handle errors but doesn't return Error objects yet renders pages containing error information which is not so useful when developing REST APIs. Error information should be sent to the clients in JSON format so that they can process it and show it to users. So....\n\nHere's Merror (/ˈmɪrə/). A simple wrapper around JavaScript Error objects with a middleware for Expressjs. Merror allows you to define a new HttpError object when you need in your controller. The object then will be passed to the middleware to be processed and sent to the client.\n\n## Usage\n\nUsing Merror is easy and straight-forward. Install `express-merror` using NPM or Yarn and import `Merror` and `MerrorMiddlware` in your application.\n\n```bash\n$ npm install --save express-merror\n```\n\n```js\n// If using TypeScript and ES6:\nimport { Merror, MerrorMiddleware } from 'express-merror';\n\n// If using JS/RequireJS\nconst MerrorModule = require('express-merror');\nconst Merror = MerrorModule.Merror;\nconst MerrorMiddleware = MerrorModule.MerrorMiddleware;\n```\n\nRegister `MerrorMiddleware` in your Expressjs application as a middleware **after registering router module** and start constructing Merror Objects whenever you hit an error in your controllers. Let's see an example:\n\n```js\nconst express = require(\"express\");\nconst cors = require(\"cors\");\nconst app = express();\nconst router = express.Router();\n\n// Some other middleware\napp.use(cors());\n\n// Register Routing Module\napp.use(\"/\", router);\n\n// Router\nrouter.post(\"/profile\", function(req, res) {\n  // Pay attention that we should wrap our error object\n  // with next() in order to make it travel to our middleware\n  // which is registered after router module\n    return next(new Merror(401, \"Unauthorized Access! Custom Message!\", {code: 1001,status: \"REFRESH_TOKEN\"} ));\n});\n\n\n// Merror Middleware\napp.use(MerrorMiddleware());\n\n// Router Module\napp.listen(3000, () =\u003e console.log(\"Example app listening on port 3000!\"));\n\n```\n\nIf we make a request to `http://localhost:3000/profile` we will see this in the body of the response:\n\n```JSON\n{\n  \"success\": false,\n  \"statusCode\": 401,\n  \"error\": \"Unauthorized\",\n  \"message\": \"Unauthorized Access!\",\n  \"properties\": {\n    \"code\": 1001,\n    \"status\": \"REFRESH_TOKEN\"\n  }\n}\n```\n\n\u003e _**NOTE:**_\n\u003e Please pay attention that you should register the middleware after registering routes and also wrap constructed error with next() function and return it in order for Merror to work properly.\n\n\n## API\n\n### `new Merror(statusCode, message, [properties])`\n\nCreates a new `Merror` object with given `statusCode` and `message`. You're free to take control of what you pass as `properties` it will be included in the response.\n\n```js\napp.post(\"/login\", function(req, res) {\n    return next(new Merror(500, \"Internal Server Error\", {code: 1021,status: \"USER_NOT_FOUND\"} ));\n});\n```\n\nAssuming we have [`express-validator`](https://github.com/ctavan/express-validator) middleware in our application we can do this:\n\n```js\napp.post(\"/login\", function(req, res) {\n  req.assert(\"email\", \"Provided email is not correct\").isEmail().notEmpty();\n  req.assert(\"password\", \"Password is not valid\").isLength({ min: 8 }).notEmpty();\n\n  const errors = req.validationErrors(true);\n\n  if (errors) {\n    return next(new Merror(403, \"Authentication Failed. Invalid Email or Password.\", errors));\n  }\n\n  // Rest of our code to find user, etc.\n});\n```\n\nNow if we POST an invalid email to this route we can see this in the response: \n\n```JSON\n{\n    \"success\": false,\n    \"statusCode\": 403,\n    \"error\": \"Forbidden\",\n    \"message\": \"Authentication Failed. Invalid Email or Password.\",\n    \"properties\": {\n        \"email\": {\n            \"location\": \"body\",\n            \"param\": \"email\",\n            \"msg\": \"Provided email is not correct\",\n            \"value\": false\n        }\n    }\n}\n```\n\n### `MerrorMiddleware()`\nReturns a simple handler that takes errors constructed in our router and sends a response with corresponding `statusCode`, `message` and `properties` if provided.\n\n```js\n// Router Module\napp.get('/', (req, res) =\u003e next(new Merror(404, \"Not Found!\")))\n\n// Register Middleware here after all routes\napp.use(MerrorMiddleware());\n```\n\n## License\n\nThis project is licensed under MIT. Feel free to fork, change and use it however you like.\n\n## Contribution\n\nIf you feel there's something that could be better in this module make sure to fork, make changes and make a new PR with full description of what you've changed. I'll make sure to review it.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmamsoudi%2Fmerror","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmamsoudi%2Fmerror","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmamsoudi%2Fmerror/lists"}