Introduction

Error handling is a critical aspect of writing robust and reliable software in Go. In this guide, we'll explore error handling techniques, how to create and handle errors, and provide sample code to demonstrate their usage.


Errors in Go

In Go, errors are represented as values of the built-in error interface type. An error value can be created using the errors.New function or through custom error types that implement the error interface.


Returning Errors

Functions in Go often return errors as a second return value. It's a common practice to check this error value to determine if an operation was successful. Here's an example:

                            package main
import (
"errors"
"fmt"
)
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
func main() {
result, err := divide(10, 2)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Result:", result)
}
}

In this code, the divide function returns an error if the denominator is zero, and the caller checks for the error before using the result.


Custom Error Types

You can create custom error types by implementing the error interface. This allows you to add additional information to errors. Here's an example:

                            package main
import (
"fmt"
)
type CustomError struct {
ErrorCode int
Description string
}
func (e *CustomError) Error() string {
return fmt.Sprintf("Error %d: %s", e.ErrorCode, e.Description)
}
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, &CustomError{ErrorCode: 100, Description: "division by zero"}
}
return a / b, nil
}
func main() {
result, err := divide(10, 0)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Result:", result)
}
}

In this code, a custom error type CustomError is created, and the divide function returns an instance of this custom error.


Error Handling Techniques

When dealing with errors in Go, various techniques are available, including logging errors, returning errors to the caller, and using panic and recover for exceptional situations.


Further Resources

To continue learning about error handling in Go, consider these resources: