ProgramGuru

The error Interface

Start with The error Interface

The built-in error type is an interface requiring one method: Error() string.

What you’ll learn

  • Explain the main purpose of the error interface.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

A type with an Error() string method satisfies the error interface. errors.New produces a basic error value, and fmt.Errorf formats a message as an error.

Printing an error generally displays its Error() string. An interface can contain a dynamic pointer value, so be careful returning a typed nil pointer as error: the resulting interface can be non-nil even when the pointer is nil.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for error interfaceAny type with Error() string satisfies the interface.Problem structStep 1Error() stringStep 2Satisfies errorStep 3Caller prints messageStep 4Any type with Error() string satisfies the interface.
Any type with Error() string satisfies the interface.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import "fmt"

type Problem struct{ Code int }

func (p Problem) Error() string { return fmt.Sprintf("problem code %d", p.Code) }
func main() {
	var err error = Problem{Code: 404}
	fmt.Println("Error:", err)
	fmt.Println("Is non-nil:", err != nil)
}

Output

Error: problem code 404
Is non-nil: true

Trace what the program does

Problem has the required Error() string method, so it satisfies error. The interface contains a Problem value, its message is printed, and comparison with nil is true.

Avoid common mistakes

  • Error() must return a string with the correct signature.
  • An error interface containing a typed nil pointer is not a nil interface.

Try it yourself

Change the custom error code to 403 and predict the message returned by Error().

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

Which method is required by the error interface?
Choose one answer. You can try again.

Answer and explanation

Error() string

Correct. Problem has the required Error() string method, so it satisfies error.

What you should remember

You have practiced The error Interface in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Returning Errors from Functions →