Error Handling



CUE has its own error type which implements Go’s error interface. We can use the cue/errors package in order to unpack and print them.

errors.go

package main

import (
	"fmt"

	"cuelang.org/go/cue"
	"cuelang.org/go/cue/cuecontext"
	"cuelang.org/go/cue/errors"
)

const schema = `
#schema: {
	i: int
	s: string
}
`

const val = `
v: #schema & {
	i: "hello"
	s: 1
}
`

func main() {
	c := cuecontext.New()
	s := c.CompileString(schema, cue.Filename("schema.cue"))
	v := c.CompileString(val, cue.Scope(s), cue.Filename("val.cue"))

	// check for errors during compiling
	if v.Err() != nil {
		msg := errors.Details(v.Err(), nil)
		fmt.Printf("Compile Error:\n%s\n", msg)
	}

	// To get all errors, we need to validate
	err := v.Validate()
	if err != nil {
		msg := errors.Details(err, nil)
		fmt.Printf("Validate Error:\n%s\n", msg)
	}
}

go run errors.go

Compile Error:
v.i: conflicting values int and "hello" (mismatched types int and string):
    schema.cue:3:5
    val.cue:3:5

Validate Error:
v.i: conflicting values int and "hello" (mismatched types int and string):
    schema.cue:3:5
    val.cue:3:5
v.s: conflicting values string and 1 (mismatched types string and int):
    schema.cue:4:5
    val.cue:4:5

You can find more information on pkg.go.dev cue/errors.

We'll never share your email with anyone else.
2024 Hofstadter, Inc