npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

joi-error-msg

v1.0.3

Published

A helper to show Joi errors as nicely formatted strings

Downloads

5

Readme

Joi Error Msg

A helper to show Joi errors as nicely formatted strings

Joi's validation functions retrieve detailed errors when schemas are not validated. But they are not ready to be shown to your users.

  • The validate function returns error details without throwing:
const { error, value } = Joi.number().integer().validate(5.5)

/*
{
  value: 5.5,
  error: [Error [ValidationError]: "value" must be an integer] {
    _original: 5.5,
    details: [
      {
        message: '"value" must be an integer',
        path: [],
        type: 'number.integer',
        context: { label: 'value', value: 5.5 }
      }
    ]
  }
}
*/
  • The assert function lets you throw errors when a schema is not validated:
Joi.assert(5.5, Joi.number().integer())

/*
Uncaught Error [ValidationError]: "value" must be an integer
    at Object.exports.process (/some/project/node_modules/.pnpm/[email protected]/node_modules/joi/lib/errors.js:193:16)
    at Object.internals.entry (/some/project/node_modules/.pnpm/[email protected]/node_modules/joi/lib/validator.js:153:26)
    at Object.exports.entry (/some/project/node_modules/.pnpm/[email protected]/node_modules/joi/lib/validator.js:27:30)
    at internals.Base.validate (/some/project/node_modules/.pnpm/[email protected]/node_modules/joi/lib/base.js:548:26)
    at Object.internals.assert (/some/project/node_modules/.pnpm/[email protected]/node_modules/joi/lib/index.js:225:27)
    at Object.assert (/some/project/node_modules/.pnpm/[email protected]/node_modules/joi/lib/index.js:102:19) {
  _original: 5.5,
  details: [
    {
      message: '"value" must be an integer',
      path: [],
      type: 'number.integer',
      context: [Object]
    }
  ]
}
*/
  • The attempt function will return value if ok, and throw if not:
const x = Joi.attempt(5.5, Joi.number().integer())

/*
Uncaught Error [ValidationError]: "value" must be an integer
    at Object.exports.process (/some/project/node_modules/.pnpm/[email protected]/node_modules/joi/lib/errors.js:193:16)
    at Object.internals.entry (/some/project/node_modules/.pnpm/[email protected]/node_modules/joi/lib/validator.js:153:26)
    at Object.exports.entry (/some/project/node_modules/.pnpm/[email protected]/node_modules/joi/lib/validator.js:27:30)
    at internals.Base.validate (/some/project/node_modules/.pnpm/[email protected]/node_modules/joi/lib/base.js:548:26)
    at Object.internals.assert (/some/project/node_modules/.pnpm/[email protected]/node_modules/joi/lib/index.js:225:27)
    at Object.assert (/some/project/node_modules/.pnpm/[email protected]/node_modules/joi/lib/index.js:102:19) {
  _original: 5.5,
  details: [
    {
      message: '"value" must be an integer',
      path: [],
      type: 'number.integer',
      context: [Object]
    }
  ]
}
*/

Usage

import Joi from 'joi'
import { validate, assert, multiAssert, attempt } from 'joi-error-msg'

// validate (value, schema, mentionWrongValueWith = '')
// Gets error msg, if any
let errorMsg = validate('a', Joi.number().integer().label('Value')) // use joi's label to define value's name
/* '➤ Value must be a number' */
validate('b', Joi.number().integer().label('Height'), 'is no good!')
/* '➤ "b" is no good! Height must be a number' */

// assert (titleMsg = '', value, schema, mentionWrongValueWith = '', titleMsg = '')
// Throw if error
try {
  const schema = Joi.array().min(1).items(
      Joi.valid('A', 'B', 'C').label('Value')
    ).label('Values')

  assert(['D'], schema, '', 'Error checking values!')
} catch (e) {
  console.error(e)
}
/*
Error checking values!
➤ Value must be one of [A, B, C]
*/

// multiAssert (titleMsg = '', ...validates)
// Validate multiple schemas, and throw if any errors
try {
  multiAssert('Error defining graph!',
    validate('a', Joi.number().integer().required().label('X coordinate')),
    validate('b', Joi.number().integer().required().label('Y coordinate'))
  )
} catch (e) {
  console.error(e)
}
/*
Error: Error defining graph!
➤ X coordinate must be a number
➤ Y coordinate must be a number
*/

// attempt (titleMsg = '', value, schema, mentionWrongValueWith = '', titleMsg = '')
try {
  let x = attempt(3, Joi.number().integer().required().label('Value'), 'is wrong.')
  /* x = 3 */

  x = attempt('a', Joi.number().integer().required().label('Value'), 'is wrong.')
} catch (e) {
  console.error(e)
}
/* '➤ "a" is wrong. Value must be a number' */

Advanced usage

The bullets in error list can be configured. E.g.:

import { config as joiMsgConfig } from 'joi-error-msg'

joiMsgConfig({ bullet: '*' })

Error messages can be colored with functions. For example, simply use chalk

import { config as joiMsgConfig } from 'joi-error-msg'
import chalk from 'chalk'

joiMsgConfig({ color: chalk.yellow, titleColor: chalk.red })

Note that if you already have a Joi error, you could use just the error formatting function:

import Joi from 'joi'
import errorMsg from 'joi-error-msg'
// errorMsg (joiError, mentionWrongValueWith = '')

const { error, value } = Joi.number().integer().validate(5.5)
if (error) console.error(errorMsg(error))

Other projects similar to this