G

Error Handling

Go syntax guide

Managing errors with multiple return values and the error type

Error Handling

Managing errors with multiple return values and the error type

Go error handling (go)
        
          package main

import (
    "errors"
    "fmt"
    "strconv"
)

// Custom error types
type ValidationError struct {
    Field   string
    Message string
}

func (e ValidationError) Error() string {
    return fmt.Sprintf("validation error on field '%s': %s", e.Field, e.Message)
}

type NetworkError struct {
    Code    int
    Message string
}

func (e NetworkError) Error() string {
    return fmt.Sprintf("network error %d: %s", e.Code, e.Message)
}

// Function that returns an error
func divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, errors.New("division by zero")
    }
    return a / b, nil
}

// Function with custom error
func validateAge(age int) error {
    if age < 0 {
        return ValidationError{Field: "age", Message: "cannot be negative"}
    }
    if age > 150 {
        return ValidationError{Field: "age", Message: "seems unrealistic"}
    }
    return nil
}

// Function that can return different error types
func processUserData(data map[string]interface{}) error {
    // Simulate network call
    if data["network_error"] != nil {
        return NetworkError{Code: 500, Message: "server error"}
    }

    if name, ok := data["name"].(string); !ok {
        return ValidationError{Field: "name", Message: "must be string"}
    } else if name == "" {
        return ValidationError{Field: "name", Message: "cannot be empty"}
    }

    if age, ok := data["age"].(float64); !ok {
        return ValidationError{Field: "age", Message: "must be number"}
    } else {
        return validateAge(int(age))
    }
}

// Panic and recover
func riskyOperation() {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Recovered from panic:", r)
        }
    }()

    // Simulate a panic
    panic("something went wrong!")
}

// Error wrapping (Go 1.13+)
func processFile(filename string) error {
    data, err := readFile(filename)
    if err != nil {
        return fmt.Errorf("failed to process file %s: %w", filename, err)
    }
    return processData(data)
}

// Mock functions for demonstration
func readFile(filename string) ([]byte, error) {
    if filename == "" {
        return nil, errors.New("filename cannot be empty")
    }
    return []byte("file content"), nil
}

func processData(data []byte) error {
    if len(data) == 0 {
        return errors.New("data cannot be empty")
    }
    return nil
}

func main() {
    // Basic error handling
    result, err := divide(10, 0)
    if err != nil {
        fmt.Println("Error:", err)
    } else {
        fmt.Printf("Result: %.2f\n", result)
    }

    // Custom errors
    if err := validateAge(-5); err != nil {
        fmt.Println("Validation error:", err)
        // Type assertion to access custom error fields
        if valErr, ok := err.(ValidationError); ok {
            fmt.Printf("Field: %s, Message: %s\n", valErr.Field, valErr.Message)
        }
    }

    // Process user data
    userData := map[string]interface{}{
        "name": "John",
        "age":  25,
    }

    if err := processUserData(userData); err != nil {
        fmt.Println("User data error:", err)
    }

    // Panic and recover
    fmt.Println("About to run risky operation...")
    riskyOperation()
    fmt.Println("Program continues after recovery")

    // Error wrapping
    if err := processFile(""); err != nil {
        fmt.Println("Wrapped error:", err)
        // Check if error wraps another error
        if wrappedErr := errors.Unwrap(err); wrappedErr != nil {
            fmt.Println("Original error:", wrappedErr)
        }
    }
}
        
      

Explanation

Go handles errors by returning them as the last return value of a function. The caller then explicitly checks if the error is nil (no error) or not.

Common Use Cases

  • Validating function inputs
  • Handling file I/O failures
  • Managing network communication issues

Related Go Syntax

Master Error Handling in Go

Understanding error handling is fundamental to writing clean and efficient Go code. This comprehensive guide provides you with practical examples and detailed explanations to help you master this important concept.

Whether you're a beginner learning the basics or an experienced developer looking to refresh your knowledge, our examples cover real-world scenarios and best practices for using error handling effectively in your Go projects.

Key Takeaways

  • Validating function inputs
  • Handling file I/O failures
  • Managing network communication issues