Day 10: Best Practices for Error Handling in Go

Venkat Annangi
Venkat Annangi
23/09/2024 15:56 1 min read 89 views
#golang #108 days of golang

Day 10: Best Practices for Error Handling in Go

Error handling is an important part of writing reliable and maintainable Go code. Today, we’ll explore best practices for managing errors in Go.

Step 1: Returning Errors

In Go, functions that might fail return an error as their second return value. Here’s an example:

func openFile(filename string) (*os.File, error) {
    file, err := os.Open(filename)
    if err != nil {
        return nil, err
    }
    return file, nil
}

Step 2: Propagating Errors

When you receive an error, you often need to propagate it up the call stack. Use return err to propagate errors:

func readFile(filename string) ([]byte, error) {
    file, err := openFile(filename)
    if err != nil {
        return nil, err
    }
    defer file.Close()
    
    return ioutil.ReadAll(file)
}

Step 3: Creating Custom Errors

You can create custom errors using errors.New() or fmt.Errorf() for more informative error messages:

func divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, fmt.Errorf("cannot divide by zero")
    }
    return a / b, nil
}

Practical Exercise

Write a function that opens a file, reads its content, and returns an error if the file doesn’t exist. Create a custom error message to indicate the specific issue.

Comments