@segment/ajv-human-errors
TypeScript icon, indicating that this package has built-in type declarations

2.12.0 • Public • Published

@segment/ajv-human-errors

Human-readable error messages for Ajv (Another JSON Schema Validator).

By default, Ajv error messages leave a little bit to be desired. ajv-human-errors provides an aggregate Error object that holds Ajv validation errors that are more easily readable by humans. For example, ajv-human-errors changes "must NOT have additional properties" to "The root value has an unexpected property, c, which is not in the list of allowed properties (a, d)."

You can also override the error message entirely using the "errorMessage" schema keyword, like you can with ajv-errors (see "Schema Options").

The following Ajv options must be set to true for ajv-human-errors to work with the errors returned by Ajv:

  • allErrors
  • verbose

The following features of JSON Schema are not yet implemented (but will return their "raw" Ajv error messages):

  • patternProperties
  • allOf
  • oneOf
  • Nested array schemas
  • const
  • if/then/else
  • contentEncoding/contentMediaType

Install

$ yarn add @segment/ajv-human-error

or

$ npm install @segment/ajv-human-error

Usage

import Ajv from 'ajv'
import { AggregateAjvError } from '@segment/ajv-human-errors'

const ajv = new Ajv({
  allErrors: true,
  verbose: true
})

ajv.validate({ title: 'Bag of Bytes', type: 'string' }, 1234)

const errors = new AggregateAjvError(ajv.errors)
console.log(errors.message)
// 'Bag of Bytes should be a string but it was a number.'
console.log(errors.map(({ message }) => message))
// ['Bag of Bytes should be a string but it was a number.']

The AggregateAjvError object can be passed to JSON.stringify():

[
  {
    "message": "The value at .arr should be unique but elements 1 and 4 are the same.",
    "path": "$.arr",
    "pointer": "/arr",
    "data": [0, 1, 2, 0, 1]
  }
  // ...
]

API

AggregateAjvError is an Iterable that yields AjvError errors:

import { AggregateAjvError } from '@segment/ajv-human-errors'

const errors = new AggregateAjvError(ajv.errors)

const messages = errors.map(({ message }) => message)

// or

const messages = []
for (const error of errors) {
  messages.push(error.message)
}

Each AjvError instance has the following properties:

  • pointer: JSON Pointer to the field that this error refers to.

  • path: JSON Path to the field that this error refers to.

  • message: Human-readable error message.

  • original: (Only if includeOriginalError option is set) Original Ajv error object.

  • data: (Only if includeData option is set) Value that value that failed validation. Useful for showing users what, exactly, was wrong without embedding entire values in the error message.

These fields are also available in the JSON form:

const { AggregateAjvError } = require('@segment/ajv-human-errors')

const errors = new AggregateAjvError(ajv.errors)

console.log(errors[0].toJSON())

which will log this:

{
  message: 'The value at /arr should be unique but elements 1 and 4 are the same.',
  path: '$.arr',
  pointer: '/arr',
  original: { ... },
  data: [0, 1, 2, 0, 1]
}

Options

The AggregateAjvError constructor accepts the following options:

  • fieldLabels (default: 'title') Change the labels used for fields. Allowed values:

    • 'js' JavaScript object accessor notation. Example: "The value at .for.bar should be a number but it was a string."

    • 'jsonPath' JSON Path notation. Example: "The value at $.foo.bar should be a number but it was a string."

    • 'jsonPointer' JSON Pointer notation. Example: "The value at /foo/bar should be a number but it was a string."

    • 'title' Uses the title property of the schema rule that failed validation. If your schema is:

      {
        "title": "Bag of values",
        "type": "object"
      }

      Then the resulting error message would look like: "Bag of values should be an object but it was an array."

  • includeOriginalError (default: false) Include the original Ajv error object on the data property of each error in the AggregateAjvError instance:

    const errors = new AggregateAjvError(ajv.errors, { includeOriginalError: true })
    errors.forEach(({ original }) => console.log(original))

    output:

    {
      params: { ... },
      parentSchema: { ... },
      schema: '...',
      schemaPath: '...',
      ...
    }
  • includeData (default: false) Include the value of the field that failed validation on the data property of each error in the AggregateAjvError instance.

    const errors = new AggregateAjvError(ajv.errors, { includeOriginalError: true })
    errors.forEach(({ data }) => console.log(data))

    output:

    'foobar'

Schema Options

If you want to override an error message entirely, you can set an "errorMessage" keyword in your JSON Schema. For example, this schema:

{
  "type": "string",
  "errorMessage": "should be a bag of bytes"
}

Returns this error message when validating a non-string object:

'The root value should be a bag of bytes.'

License

MIT License

Copyright (c) 2024 Segment

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Contributing

All third party contributors acknowledge that any contributions they provide will be made under the same open source license that the open source project is provided under.

Readme

Keywords

none

Package Sidebar

Install

npm i @segment/ajv-human-errors

Weekly Downloads

62,919

Version

2.12.0

License

MIT

Unpacked Size

149 kB

Total Files

43

Last publish

Collaborators

  • ssuneja
  • azhaotwilio
  • ldelossantos
  • cjo2
  • achandrashekaran
  • aparna.singhal
  • ynguyen
  • timmyzsearcy
  • igracheva-twilio
  • yashnit-segment
  • nanotimm
  • srivig21
  • chenchensegmentcom
  • sanket.mishra
  • lweimersegment
  • rcheedhalla
  • jxin_twilio
  • odoren_segment
  • aditi.raveesh
  • dltnbrks-segment
  • sai-patanjali
  • himanshuph
  • alecjacobs-segment
  • sshaikh_segment
  • john.lee1100
  • dazu70
  • brian.aguirre
  • pooja.patil
  • segment_fan
  • nlubchenco
  • jamezhutwilio
  • knksmith57-segment
  • jsh-wu
  • nithin-benny
  • poojasegment
  • ebru.odok
  • bannapple
  • rodhilton_twilio
  • guthriesegment
  • srishti-nema
  • cdelaomartinez
  • miguelpdiaz8
  • sundareswar.jayakumar
  • gbatra
  • spencerattick
  • akodankiry
  • nanette.ranes
  • gsolis_segment
  • nitinpm432
  • aadityabhatt10
  • amigandhi
  • segmentsean
  • hmohanram_seg
  • jrupasinghe
  • myrontin.segment
  • devthale
  • smccoy-twilio
  • seg-leonelsanches
  • jibrang
  • sethgrid_segment
  • light-bringer-blr
  • aubreysine
  • ed-twilion-npm
  • harsh-joshi99
  • irfan.ali.segment
  • kbhargavaram-sg
  • needcaffeine
  • nat-grid
  • wlumsegment
  • vivek-26
  • moyara2
  • bala.singareddy
  • gbbastos
  • akash.gautam07
  • preetyp
  • viveksainaneesegment
  • msaraf
  • kjoerres
  • rokatyal
  • ainatancinco
  • anton-vylushchak
  • sowjanyasegment
  • alayvora
  • msaunders-segment
  • tw-dgarcia
  • parag.panda
  • blangtwilio
  • ryanrouleau-segment
  • twjosiah
  • mcullenmeyer
  • david.anusontarangkul.segment
  • mckern_segment
  • segment-admin
  • nainy.agrawal
  • tdibacco
  • sudojatin
  • nageshgolem
  • brandonheyer-segment
  • alfrimpong
  • dobrin.ganev
  • ankit.gupta.unthinkable
  • marinhero
  • benattwilio
  • bharath.boregowda
  • conniechen
  • sungju.jin
  • pooyaj
  • yli119
  • ea_segment
  • emilyjia
  • kx-segment
  • xinghao.huang
  • harsh.vardhan
  • joe.ayoub.segment
  • gkochar123
  • rollcode
  • ariel.silvestri
  • cherylj-segment
  • immanoj
  • aaronklish
  • michelr
  • maneesh.dharma29
  • msolorzano-segment
  • brianhumphreystwilio
  • jfehrman.segment
  • joetessy
  • pmunin
  • jalexy12
  • jbandi-twilio
  • prayansh-twilio
  • dominicbarnes
  • brandon.scott-segment
  • bgillan
  • phillip.thomas
  • ricardo.rossi
  • forgetfulfellow
  • fauzy.yy
  • mayur-pitale
  • dbaik-twilio-segment
  • seg-rustybailey
  • tanya.gupta.segment
  • pmiller-twilio
  • nevermore2022
  • aishikawaki
  • csayuso
  • mcoulibali
  • shupadhyay
  • jahood-twilio
  • saisagarkappaganthula
  • rmukundan
  • arubiochavez
  • shuvrajit9904
  • s3gm3nt
  • ama0223
  • tbrennanj
  • dangmai-segment
  • shraddha-twilio
  • sa-jsooter
  • enyi.asonye
  • afsha-nazim-seg
  • mschaszberger
  • lnamba
  • varadarajan-tw
  • seanhan-segment
  • replatero
  • sayan-das-in
  • justeen
  • sausingh
  • jgabe13
  • meg1000
  • funlu
  • ashwitha.bg
  • whaider_twilio
  • tcgilbert
  • kevinburkesegment
  • felttrip
  • prabhnoor1997
  • akashyap91
  • clintz.seg
  • karimkeshwani
  • wally.tg
  • rhall-twilio
  • yash-twilio
  • brookstaylorjr
  • shayan-golafshani
  • lerahulram
  • mugelstad
  • hdamani
  • rrivera-segment
  • sethnutetwilio
  • manali-bhosale
  • chtoombs
  • sethsegment
  • eric-hyde
  • elmoselyee
  • michaelghseg
  • jayakrishnannair
  • lateefat
  • maryam.sharif
  • wdbetts
  • ryanligon
  • sindhusegment
  • lfdelossantos
  • aramakrishnan
  • segment-camden
  • vbatanov
  • lluque-twilio
  • jair.aviles
  • pmaid
  • song4you
  • peterdemartini
  • emmy.byrne
  • vincen7tran
  • dean-huynh
  • cdignam-segment
  • abhinavsureka
  • arunlalam-segment
  • cjradek
  • neeharikakondipati
  • simpixelated
  • chihchun-twilio
  • acharles14
  • jyim008
  • hema-segment
  • oscb
  • krousseau
  • sachinwathore
  • fhalim-segment
  • cfree
  • hjoonpm
  • celine-segment
  • pmcanseco-segment
  • masira
  • amillet89
  • cholt002
  • av-segment
  • aghotikar
  • vikrant-segment
  • larryatsegment
  • ariel_segment
  • scruwys1
  • kyliepedersen
  • jinapark
  • segmentio
  • rajulvadera
  • lpediredla
  • n2parko
  • tyson_segment
  • bgamwell
  • uditmehta
  • salolivares
  • erikdw
  • chenxiangzhang
  • mericsson
  • prayansh-segmentt
  • jeremylarkin
  • bsneed
  • danieljackins
  • segment-seth
  • james9446
  • priscilla.giatti
  • nlsun
  • drew-thompson
  • segment-jsingh
  • andrius-segment
  • valerieernst
  • kelcook
  • gilomer
  • marcelopv
  • eric.rogner
  • kdharaiya
  • jon.anderson-at-segment.com
  • stacy.song
  • rexatsegment
  • nickaguilar
  • bradenbecker
  • reneewang
  • dan.lasky
  • sam.tapia
  • vikramkumar19
  • mpriyad25
  • jeremy.parker
  • smidges