Codecademy Logo

Effective Error Handling in Go

Built-in Error Interface

Go contains a built-in error type implemented as an interface containing an Error() function that returns a string.

type error interface {
Error() string
}

Errors as Return Values

In Go, errors are values returned by functions and treated similarly to any other datatype.

func connectToDatabase(config dbConfig) (&dbConnection, error) {
conn, err := DB.Connect(config)
if err != nil {
return nil, fmt.Errorf("cannot connect to database: %w", err)
}
return conn, nil
}

Custom Error Types

Custom error types in Go enable embedding additional context, such as function parameters or timestamps to improve error handling and recovery.

type FileParseError struct {
FileName string
Line int
Reason string
}
func (e FileParseError) Error() string {
return fmt.Sprintf("error parsing file %s at line %d: %s", e.FileName, e.Line, e.Reason)
}

Panic and Recover

Go’s panic() and recover() functions provide a way to handle unexpected errors and enable controlled recovery.

func divide(a, b int) (result int, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("error while dividing: %v", r)
}
}()
result = a / b
return result, err
}

Wrapping Errors with Context

Go allows wrapping errors with additional context using %w to enhance error handling across function calls.

func convertToInt(value string) (int, error) {
result, err := strconv.Atoi(value)
if err != nil {
return 0, fmt.Errorf("conversion error: unable to convert '%s' to integer: %w", value, err)
}
return result, nil
}

Learn More on Codecademy