{"id":17458110,"url":"https://github.com/pocesar/js-joi-match-error","last_synced_at":"2025-04-02T21:30:17.724Z","repository":{"id":57281411,"uuid":"150901529","full_name":"pocesar/js-joi-match-error","owner":"pocesar","description":"A simple (and convenient) wrapper for passing to Joi.error() ","archived":false,"fork":false,"pushed_at":"2018-09-30T03:27:51.000Z","size":7,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":3,"default_branch":"master","last_synced_at":"2024-10-18T06:27:59.520Z","etag":null,"topics":["custom-error","error","error-handling","joi","joi-validation","match","matching"],"latest_commit_sha":null,"homepage":null,"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/pocesar.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}},"created_at":"2018-09-29T20:42:31.000Z","updated_at":"2019-05-26T01:43:10.000Z","dependencies_parsed_at":"2022-09-19T21:54:25.435Z","dependency_job_id":null,"html_url":"https://github.com/pocesar/js-joi-match-error","commit_stats":null,"previous_names":[],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pocesar%2Fjs-joi-match-error","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pocesar%2Fjs-joi-match-error/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pocesar%2Fjs-joi-match-error/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pocesar%2Fjs-joi-match-error/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/pocesar","download_url":"https://codeload.github.com/pocesar/js-joi-match-error/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246895552,"owners_count":20851290,"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":["custom-error","error","error-handling","joi","joi-validation","match","matching"],"created_at":"2024-10-18T03:54:33.345Z","updated_at":"2025-04-02T21:30:17.693Z","avatar_url":"https://github.com/pocesar.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"[![Build Status](https://travis-ci.org/pocesar/js-joi-match-error.svg?branch=master)](https://travis-ci.org/pocesar/js-joi-match-error)\n[![npm version](https://badge.fury.io/js/joi-match-error.svg)](https://badge.fury.io/js/joi-match-error)\n\n# js-joi-match-error\n\nA simple (and convenient) wrapper for passing to Joi.error()\n\n## Why?\n\nJoi makes custom validation errors really really really really hard. There's no \"catch all\", there's no way to do one `error()`\nfor every new object you create. So it's best to just try and match them like a switch statement.\n\n## How?\n\n```\nnpm i joi-match-error\n```\n\n```js\nimport Joi from 'joi'\nimport { MatchError } from 'joi-match-error'\n\nconst MySchema = Joi.string().required().min(10).max(15).label('Some string').error(\n  MatchError({\n    'any.required': 'You must provide Some String',\n    'string.min': (err) =\u003e (`${err.context.label} needs at least ${err.context.limit} chars`),\n    'string.max': (err) =\u003e (`${err.context.label} needs to be at most ${err.context.limit} chars`),\n    fallback: 'Invalid string'\n  })\n)\n\nMySchema.validate('asdf').error // yields \"Some string needs at least 10 chars\"\n```\n\nYou may pass a custom error constructor as the second parameter, so you may wrap the joi `ValidationError` into something else (happens after the matching, and should return an instance of `Error`):\n\n```js\nMatchError({\n  fallback: (err) =\u003e (err.message),\n}, (originalErrors, matched, matchedIndex) =\u003e {\n  // originalErrors = Array\u003cValidationErrorItem\u003e\n  // Matched = resulting string, in that case, originalErrors[0].message\n  // matchedIndex = index from the errors array\n  return new MyCustomError(matched, 400, originalErrors[matchedIndex])\n})\n```\n\nWhy would you do that? So you can, for example, when returning an error to the user, be opaque with no\nfurther stacktrace info, but still useful to log the whole error on the server-side (good practices!)\n\nIf you need a generic (english only) wrapper for all your errors, it comes as `InvalidLabel` helper (just so you don't get \"child fails blah blah\")\n\n```js\nimport { InvalidLabel, MatchError } from 'joi-match-error'\n\nMatchError({\n  fallback: InvalidLabel() // returns something like the template `${err.context.label} is invalid`\n})\n\nMatchError({\n  fallback: InvalidLabel('é inválido') // returns something like the template `${err.context.label} é inválido`\n})\n```\n\nThen, your custom Joi constructor might look like this:\n\n```js\nimport { MatchError, InvalidLabel } from 'joi-match-error'\nimport Joi from 'joi'\n\n/**\n * assuming schema is a { field: Joi.[something](), field2: Joi.[another]() }\n **/\nexport const MyJoi = (schema) =\u003e {\n  return Joi.object(\n    Object.keys(schema).reduce((obj, key) =\u003e {\n      obj[key] = schema[key].error(\n        MatchError({\n          fallback: InvalidLabel()\n        })\n      )\n      return obj\n    }, {})\n  )\n}\n```\n\n## Caveats\n\n* You need to understand inner workings of Joi to be able to match the correct errors (kinda time consuming), such as the Joi Validation error types like `number.base`, or `string.creditCard`. If it helps, look at [Joi codebase](https://github.com/hapijs/joi/blob/master/lib/language.js) (unless you're using Typescript or JS with VSCode, you get all the existing keys for free :sparkling_heart:)\n* Nested errors are not supported at top level (must write down to the level you want the error on)\n* Hard to do i18n, unless you wrap the wrapper (yo dawg)\n* Returns only the first error, since Joi returns an array of errors even for a single one, so it's brute force-y\n\n## License\n\nMIT\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpocesar%2Fjs-joi-match-error","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpocesar%2Fjs-joi-match-error","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpocesar%2Fjs-joi-match-error/lists"}