yq/operators/error.md
2022-10-29 18:24:11 +11:00

1020 B

Error

Use this operation to short-circuit expressions. Useful for validation.

Validate a particular value

Given a sample.yml file of:

a: hello

then

yq 'select(.a == "howdy") or error(".a [" + .a + "] is not howdy!")' sample.yml

will output

Error: .a [hello] is not howdy!

Validate the environment variable is a number - invalid

Running

numberOfCats="please" yq --null-input 'env(numberOfCats) | select(tag == "!!int") or error("numberOfCats is not a number :(")'

will output

Error: numberOfCats is not a number :(

Validate the environment variable is a number - valid

with can be a convenient way of encapsulating validation.

Given a sample.yml file of:

name: Bob
favouriteAnimal: cat

then

numberOfCats="3" yq '
	with(env(numberOfCats); select(tag == "!!int") or error("numberOfCats is not a number :(")) | 
	.numPets = env(numberOfCats)
' sample.yml

will output

name: Bob
favouriteAnimal: cat
numPets: 3