Fundamentals

Error Handling

Return, wrap, inspect, and design errors so that failures are visible and useful.

What you will learn

Programs fail: files go missing, networks drop, users type nonsense. Go handles failure with ordinary values rather than exceptions. This lesson covers how to return and check errors, how to add context by wrapping, how to test for specific errors with errors.Is and errors.As, how to define your own errors, and where panic fits in.

Errors are values

Many languages use try/catch, which jumps out of the current code when something fails. Go has no exceptions. A function that can fail returns an error as its last result, and the caller checks it:

data, err := os.ReadFile("config.json")
if err != nil {
    fmt.Println("could not read config:", err)
    return
}
fmt.Println(len(data), "bytes read")

If err is nil, the call worked. If it is not nil, something went wrong and the other results should not be trusted. You will write if err != nil many times, and that is by design: every place that can fail is visible in the code, right next to the success path.

The error interface

error is a tiny built-in interface:

type error interface {
    Error() string
}

Any type with an Error() string method is an error. That is the entire mechanism, and it uses what you learned in the interfaces lesson.

Creating errors

The simplest way is errors.New:

func divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, errors.New("divisor must not be zero")
    }
    return a / b, nil
}

For a message with values in it, use fmt.Errorf:

return fmt.Errorf("user %d not found", id)

By convention, error messages start with a lowercase letter and do not end with punctuation. This is because they often get joined into longer messages such as load profile: user 42 not found.

Checking errors

Handle the error immediately, before using any other result:

result, err := divide(10, 0)
if err != nil {
    fmt.Println("error:", err)
    return
}
fmt.Println(result)

It is tempting to ignore an error with _, as in result, _ := divide(10, 0). Do that only when you are sure failure is impossible or harmless, because silent failures are very hard to debug.

Adding context by wrapping

A bare error such as open config.json: no such file or directory tells you what failed, but not what your program was trying to do. As an error travels up through functions, each layer can add context with the %w verb:

func loadConfig(path string) ([]byte, error) {
    data, err := os.ReadFile(path)
    if err != nil {
        return nil, fmt.Errorf("load config: %w", err)
    }
    return data, nil
}

The resulting message reads like a trail: load config: open settings.json: no such file or directory. Crucially, %w wraps the original error rather than just copying its text, so the original is still available for inspection. If you use %v instead, the message looks the same but the connection is lost.

A good context message says what operation failed and, where useful, which input was involved.

Inspecting errors

Never compare errors by their message text. Messages are for humans and may change. Use these two functions instead.

errors.Is asks "is this error, or anything it wraps, this particular error?":

_, err := loadConfig("missing.json")

if errors.Is(err, os.ErrNotExist) {
    fmt.Println("config file does not exist, using defaults")
}

It works even though loadConfig wrapped the original error, because errors.Is unwraps layer by layer.

errors.As asks "is there an error of this type in the chain?", and gives you access to it:

var pathErr *fs.PathError
if errors.As(err, &pathErr) {
    fmt.Println("operation:", pathErr.Op)
    fmt.Println("path:", pathErr.Path)
}

Note the &pathErr: errors.As needs a pointer so it can fill the variable in.

Sentinel errors

A package can export a fixed error value for callers to check, called a sentinel error:

var ErrNotFound = errors.New("not found")

func findUser(id int) (User, error) {
    // ...
    return User{}, fmt.Errorf("find user %d: %w", id, ErrNotFound)
}

Callers test it with errors.Is(err, ErrNotFound). Sentinel errors are part of your package's public API, so create them only for conditions callers truly need to tell apart.

Custom error types

When callers need structured details, define a type:

type ValidationError struct {
    Field   string
    Message string
}

func (e ValidationError) Error() string {
    return e.Field + ": " + e.Message
}

func validateAge(age int) error {
    if age < 0 {
        return ValidationError{Field: "age", Message: "must not be negative"}
    }
    return nil
}

A caller can then pull out the details:

err := validateAge(-5)

var ve ValidationError
if errors.As(err, &ve) {
    fmt.Println("bad field:", ve.Field) // bad field: age
}

Handle it or return it, not both

A common mistake is to log an error and also return it, so every layer logs the same failure again. Pick one job per layer:

  • Return it, with added context, if this function cannot decide what to do.
  • Handle it fully, by retrying, falling back, or reporting to the user, if it can.

Log once, at the outer boundary where the program makes its final decision.

Combining errors

When several things can fail independently, such as validating many fields, errors.Join combines them into one error:

err := errors.Join(errors.New("name is empty"), errors.New("age is negative"))
fmt.Println(err)
// name is empty
// age is negative

errors.Is and errors.As look inside a joined error too.

panic is different

A panic stops the normal flow of the program, runs deferred calls, and then crashes it with a stack trace. It is not Go's way of handling expected problems. Use errors for things that can reasonably go wrong, such as bad input, a missing file, or a network timeout. Reserve panic for situations that should never happen, such as a broken internal assumption, or for failures at startup where continuing makes no sense.

func mustPositive(n int) int {
    if n <= 0 {
        panic("n must be positive")
    }
    return n
}

A panic can be intercepted with recover inside a deferred function, but this is for special cases like a web server protecting itself from one bad request. Libraries should almost never panic on conditions a caller could handle.

Common mistakes

  • Ignoring errors with _ without a good reason.
  • Comparing error strings. Use errors.Is and errors.As.
  • Using %v instead of %w and losing the original error.
  • Logging and returning the same error.
  • Capitalising or punctuating messages such as "Failed to load.", which look odd once wrapped.
  • Returning a typed nil pointer as an error. See the interfaces lesson.

Practice

Write LoadPort(path string) (int, error). It should read a file, convert its contents to an integer, and reject any port outside 1 to 65535. Add context to each failure and keep the wrapped errors. In main, call it with a path that does not exist and use errors.Is to detect the missing file.

Summary

In Go, an error is an ordinary value, returned as the last result and checked immediately with if err != nil. The error interface needs only an Error() string method. Add context as errors travel upward with fmt.Errorf and %w, and inspect them with errors.Is for known values and errors.As for types, never by comparing text. Each layer should either handle an error or return it, and panic is for situations that should never happen, not for ordinary failures.

Official reference: Working with errors in Go 1.13 and Effective Go: Errors.

Ready to wrap up?

Mark this complete when you can explain the main idea and finish the practice task.

Copyright © 2026