Go contains a built-in error type implemented as an interface containing an Error()
function that returns a string.
type error interface {Error() string}
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 in Go enable embedding additional context, such as function parameters or timestamps to improve error handling and recovery.
type FileParseError struct {FileName stringLine intReason string}func (e FileParseError) Error() string {return fmt.Sprintf("error parsing file %s at line %d: %s", e.FileName, e.Line, e.Reason)}
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 / breturn result, err}
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}