github.com/kaptinlin/jsonschema@v0.4.6/examples/error-handling/main.go (about)

     1  package main
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"log"
     7  
     8  	"github.com/kaptinlin/jsonschema"
     9  )
    10  
    11  func main() {
    12  	// Schema with various constraints
    13  	compiler := jsonschema.NewCompiler()
    14  	schema, err := compiler.Compile([]byte(`{
    15  		"type": "object",
    16  		"properties": {
    17  			"name": {"type": "string", "minLength": 2, "maxLength": 50},
    18  			"age": {"type": "integer", "minimum": 18, "maximum": 120},
    19  			"email": {"type": "string", "format": "email"},
    20  			"score": {"type": "number", "minimum": 0, "maximum": 100}
    21  		},
    22  		"required": ["name", "age", "email"]
    23  	}`))
    24  	if err != nil {
    25  		log.Fatal(err)
    26  	}
    27  
    28  	fmt.Println("Error Handling Examples")
    29  	fmt.Println("=======================")
    30  
    31  	// Example 1: Multiple validation errors
    32  	fmt.Println("1. Multiple validation errors:")
    33  	invalidData := map[string]interface{}{
    34  		"name":  "J",            // too short
    35  		"age":   15,             // under minimum
    36  		"email": "not-an-email", // invalid format
    37  		"score": 150,            // over maximum
    38  	}
    39  
    40  	result := schema.Validate(invalidData)
    41  	if !result.IsValid() {
    42  		fmt.Println("   Errors:")
    43  		for field, error := range result.Errors {
    44  			fmt.Printf("   - %s: %s\n", field, error.Message)
    45  		}
    46  	}
    47  
    48  	// Example 2: Error list format
    49  	fmt.Println("\n2. Error list format:")
    50  	errorList := result.ToList()
    51  	if len(errorList.Errors) > 0 {
    52  		for field, message := range errorList.Errors {
    53  			fmt.Printf("   - %s: %s\n", field, message)
    54  		}
    55  	}
    56  
    57  	// Example 3: JSON parse error
    58  	fmt.Println("\n3. JSON parse error:")
    59  	invalidJSON := []byte(`{"name": "John", "age": 25,}`) // trailing comma
    60  	result = schema.Validate(invalidJSON)
    61  	if !result.IsValid() {
    62  		fmt.Println("   JSON parsing failed")
    63  	}
    64  
    65  	// Example 4: Unmarshal error
    66  	fmt.Println("\n4. Unmarshal error:")
    67  	type User struct {
    68  		Name  string `json:"name"`
    69  		Age   int    `json:"age"`
    70  		Email string `json:"email"`
    71  	}
    72  
    73  	var user User
    74  	err = schema.Unmarshal(&user, invalidData)
    75  	if err != nil {
    76  		fmt.Printf("   Unmarshal failed: %v\n", err)
    77  
    78  		// Check if it's an UnmarshalError using errors.As
    79  		var unmarshalErr *jsonschema.UnmarshalError
    80  		if errors.As(err, &unmarshalErr) {
    81  			fmt.Printf("   Error type: %s\n", unmarshalErr.Type)
    82  		}
    83  	}
    84  
    85  	// Example 5: Successful validation
    86  	fmt.Println("\n5. Successful validation:")
    87  	validData := map[string]interface{}{
    88  		"name":  "John Doe",
    89  		"age":   25,
    90  		"email": "john@example.com",
    91  		"score": 95.5,
    92  	}
    93  
    94  	result = schema.Validate(validData)
    95  	if result.IsValid() {
    96  		fmt.Println("   ✅ Validation passed")
    97  	}
    98  }