cuelang.org/go@v0.13.0/cue/errors/example_test.go (about)

     1  // Copyright 2024 The CUE Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package errors_test
    16  
    17  import (
    18  	"fmt"
    19  
    20  	"cuelang.org/go/cue"
    21  	"cuelang.org/go/cue/cuecontext"
    22  	"cuelang.org/go/cue/errors"
    23  )
    24  
    25  func Example() {
    26  	v := cuecontext.New().CompileString(`
    27  		a: string & 123
    28  		b: int & "foo"
    29  	`, cue.Filename("input.cue"))
    30  	err := v.Validate()
    31  
    32  	// [error.Error] only shows the first error encountered.
    33  	fmt.Printf("string via the Error method:\n  %q\n\n", err.Error())
    34  
    35  	// [errors.Errors] allows listing all the errors encountered.
    36  	fmt.Printf("list via errors.Errors:\n")
    37  	for _, e := range errors.Errors(err) {
    38  		fmt.Printf("  * %s\n", e)
    39  	}
    40  	fmt.Printf("\n")
    41  
    42  	// [errors.Positions] lists the positions of all errors encountered.
    43  	fmt.Printf("positions via errors.Positions:\n")
    44  	for _, pos := range errors.Positions(err) {
    45  		fmt.Printf("  * %s\n", pos)
    46  	}
    47  	fmt.Printf("\n")
    48  
    49  	// [errors.Details] renders a human-friendly description of all errors like cmd/cue does.
    50  	fmt.Printf("human-friendly string via errors.Details:\n")
    51  	fmt.Println(errors.Details(err, nil))
    52  
    53  	// Output:
    54  	// string via the Error method:
    55  	//   "a: conflicting values string and 123 (mismatched types string and int) (and 1 more errors)"
    56  	//
    57  	// list via errors.Errors:
    58  	//   * a: conflicting values string and 123 (mismatched types string and int)
    59  	//   * b: conflicting values int and "foo" (mismatched types int and string)
    60  	//
    61  	// positions via errors.Positions:
    62  	//   * input.cue:2:6
    63  	//   * input.cue:2:15
    64  	//
    65  	// human-friendly string via errors.Details:
    66  	// a: conflicting values string and 123 (mismatched types string and int):
    67  	//     input.cue:2:6
    68  	//     input.cue:2:15
    69  	// b: conflicting values int and "foo" (mismatched types int and string):
    70  	//     input.cue:3:6
    71  	//     input.cue:3:12
    72  }