Skip to content
Tutorials Center
My learning

Topics

Lesson 60 of 147 ยท Errors

Errors as Values

Learn how Go handles errors - the error interface, errors.New and fmt.Errorf, returning and checking errors, the if err != nil idiom, sentinel errors like io.EOF and when to ignore an error.

Programs fail in ordinary ways: a file is missing, a number cannot be parsed, a network connection drops, a user types nonsense. Many languages deal with this through exceptions that jump out of the current function and unwind the stack until something catches them. Go takes a different route: an error is just a value, returned from a function like any other result, and you decide on the spot what to do with it.

That choice is the most visible difference between Go and languages such as Java, Python or JavaScript. It makes the failure paths of a program visible in the code, one if at a time, at the price of some repetition. This lesson explains the error type, the basic ways to create and return errors, the famous if err != nil idiom, sentinel errors such as io.EOF, and which errors it is safe to ignore. The following lessons add wrapping, custom error types, panic and recover and handling patterns.

The error interface

error is a built-in interface type with a single method:

Go
type error interface {
	Error() string
}

Any type with an Error() string method is an error. The string is the human-readable message. A function that can fail returns an error as its last result, and the value nil means "no error". You already know multiple return values; (result, error) is the standard shape.

Go Returning and checking an error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

errors.New creates a basic error holding a message. fmt.Println knows how to print any error by calling its Error method. The caller checks err != nil immediately after the call. When the error is not nil, the other result is usually meaningless (here a zero value), so you must not use it.

Creating errors with formatting

To include details such as the offending value, use fmt.Errorf, which works like Sprintf but returns an error:

Go errors.New and fmt.Errorf

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The last line prints false. Each call to errors.New returns a new error value, even if the text is identical. This is on purpose, and it is what makes sentinel errors (below) work.

Error strings are conventionally written in lower case and without trailing punctuation, because they are often embedded in longer messages: open config.json: no such file or directory, not Error: Could not open file.. Linters such as staticcheck flag deviations.

The if err != nil idiom

Go code is full of this shape:

Go
result, err := doSomething()
if err != nil {
	return err
}
// use result

It is repetitive, and newcomers often complain about it. There are good reasons it is considered a feature, though:

  • Every failure point is visible. You can read a function from top to bottom and see exactly where it can stop, with no hidden control flow.
  • Errors are handled where the context is known. You decide per call whether to retry, use a default, add context or give up.
  • Errors are ordinary values. You can store them, collect them, compare them, pass them to other functions and test them.

The accepted style is the early return: handle the error first and keep the successful path unindented.

Go A chain of fallible steps with early returns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Notice that parsePoint returns the strconv error as it is, which is fine for a small program but loses context: the caller cannot tell which coordinate was bad. Wrapping Errors solves that with %w.

Scope: err in if statements

An if statement can declare the call and the check together. The variables exist only inside the if and its else branches, which keeps a function's scope clean:

Go The err variable inside an if

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

If the result is needed after the check (the usual case), declare it before the if as the last two lines do.

Sentinel errors

Sometimes the caller needs to know which error occurred, not just that one did. The simplest mechanism is a sentinel error: a package-level variable, created once with errors.New, that functions return and callers compare against. By convention its name starts with Err.

The standard library has several. The most famous is io.EOF, returned by readers when no more data is available. It is not a failure, just the normal end of input:

Go io.EOF and your own sentinel error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Comparing with == works only if the error is returned unchanged. Once code adds context around a sentinel, == stops matching. The correct tool is errors.Is, covered in Wrapping and Inspecting Errors. Start using errors.Is(err, ErrNotFound) now if you can; it behaves like == for plain errors and keeps working later.

Never compare error text

It is tempting to write if err.Error() == "not found" or strings.Contains(err.Error(), "no such file"). Do not. Messages are meant for people, they change between Go versions and operating systems, and a translated or reworded message silently breaks the check. Compare values (errors.Is), or inspect types (errors.As, see Custom Error Types).

Real errors from the standard library

Library functions return rich errors that describe both the operation and the cause. Opening a file that does not exist gives an error whose message includes the path, and which you can test with a standard sentinel:

Go Errors from os.Open and the strconv package

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

errors.Is(err, fs.ErrNotExist) is portable across operating systems, unlike the message text. The reported type is *fs.PathError, a struct that carries the operation, the path and the underlying error; you will build similar types yourself in Custom Error Types.

What to do with an error

When a call returns an error, you have four honest options:

  1. Handle it: recover locally, for example fall back to a default value or retry.
  2. Return it, usually after adding context (next lesson), so the caller can decide.
  3. Report it at the edge of the program (log it, show it to the user, exit with a non-zero status).
  4. Ignore it deliberately, and say why in a comment.

What you should not do is both log it and return it, because the same failure then appears in the logs several times. Error Handling Patterns goes into this.

Ignoring errors safely

You can discard a result with the blank identifier _, but only do so when failure truly cannot matter or cannot happen:

Go Ignoring errors on purpose

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The first two ignores are fine; the third is a classic bug. Atoi returns 0 for bad input, which is indistinguishable from the real number zero. Ignoring errors from Close on a file you wrote to is also risky, because buffered data may only fail to reach the disk when the file is closed.

If you leave an error unchecked, Go does not complain. Run go vet and a linter (see Vet and Linting): they flag many unchecked errors. Declaring err and never using it does fail to compile, as it does for every unused variable.

A function that returns an error value as nil

A function whose return type is error returns nil on success. Be careful when assigning a custom pointer type to an error variable: a nil pointer inside a non-nil interface is not nil. That trap has its own section in Custom Error Types; for now remember to return nil explicitly rather than returning a typed variable that may be nil.

Go Who handles the error? A mini config loader

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

IntOr makes a decision for one specific error (ErrMissing) and passes every other error up. This is the everyday pattern: handle what you understand, return what you do not.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a function that can fail usually return?

    The convention is (result, error) with the error as the last return value. nil means success.
  2. 2. What does errors.New("x") == errors.New("x") evaluate to?

    errors.New returns a pointer to a new value every time, and the comparison compares those pointers. That is why sentinel errors are created once, as package variables.
  3. 3. Which code best follows the Go style for a failing call?

    Handle the error first and return early, so the successful path stays at the left margin and is easy to read.
  4. 4. Why is strings.Contains(err.Error(), "not found") a poor way to detect an error?

    Messages may be reworded or translated. Compare against a sentinel with errors.Is, or look at the type with errors.As.
  5. 5. What does io.EOF mean when returned from a reader?

    io.EOF is a sentinel error that signals a normal end of input. Loops compare against it and stop without treating it as a failure.

Summary

  • error is a built-in interface with one method, Error() string; nil means success.
  • Functions return (result, error); check the error first, return early and do not use the result when an error occurred.
  • Create errors with errors.New (fixed message) or fmt.Errorf (formatted). Messages are lower case without trailing punctuation.
  • Sentinel errors such as io.EOF or your own ErrNotFound are package-level variables compared by identity; prefer errors.Is over ==.
  • Never decide by the text of an error message.
  • Handle an error, return it, or report it at the edge; do not log and return it. Ignore errors only when failure cannot matter, and say why.

Next: Wrapping and Inspecting Errors adds context to errors with %w and inspects them with errors.Is and errors.As.