Overview

7 Errors In Go

Go treats errors as ordinary values, which keeps failure handling explicit and close to the code that may fail. Functions usually return an error as the last result, and callers check whether it is nil before continuing. This approach favors clarity over hidden control flow, making it easy to see which operations can fail and to decide right away whether to return, retry, log, or otherwise respond.

The chapter shows how to create and use errors in several ways, starting with simple messages from errors.New and formatted context from fmt.Errorf. It then moves to sentinel errors, which are reusable named values that represent common conditions such as conflicts or missing data, and explains how errors.Is helps detect them even when errors are wrapped. It also demonstrates custom error types that carry extra information, such as a list of missing keys, and how errors.As can extract that underlying type for more detailed handling.

For reporting, the text emphasizes adding context when logging or rewrapping errors so that failures are easier to diagnose. It then discusses exceptional situations with panic and recover, using them only when a program cannot safely continue or when an unrecoverable internal state demands an immediate stop. In most cases, the guidance is to avoid panic, prefer ordinary error returns, and handle problems as early and clearly as possible.

Summary

  • Errors in Go are values returned from a function, typically as the last return value.
  • Values of any type can be errors, so long as that type implements the error interface by defining an Error() string method.
  • Errors should be handled as soon as possible where they are returned, typically by returning them to the calling function with meaningful annotation, if necessary.
  • When writing your packages, try to make the errors you return relevant to the function of that package. Using your error types can be helpful here. Try not to return errors without this context, such as errors from other packages or those that wrap them. Correspondingly, make sure to wrap errors from within your package that might otherwise be obscured.
  • If you need to test for a particular error, use errors.Is() to check for it. If you need to test for a particular error type, use errors.As().
  • Panics indicate a condition that is truly unexpected and should be treated with care since they break the normal control flow of your program. panic is not intended as an error-handling mechanism, and if the structure of your program necessitates a panic, you need to document this possibility. Otherwise, use ordinary errors.

FAQ

What is the main idea behind Go’s error handling approach?Go treats errors as ordinary values rather than exceptions. Functions return an error value alongside other results, and callers check whether it is nil to determine success or failure.
What does the built-in error type look like in Go?error is a simple interface with one method: Error() string. Any type that implements this method can be used as an error.
Where should an error usually appear in a function’s return values?By convention, an error is returned as the final value, or as the only return value if the function can fail and returns nothing else.
How do you check whether a Go function failed?You compare the returned error to nil. If it is not nil, the function failed and you should handle the error immediately.
What is the difference between errors.New and fmt.Errorf?errors.New creates a simple error from a static string, while fmt.Errorf lets you create formatted errors and add more context, making it more flexible for real programs.
What is a sentinel error in Go?A sentinel error is a predefined, unique error value used to represent a specific condition, such as ErrNotExist or ErrConflict. They are often compared with errors.Is().
How do you check whether an error matches a sentinel error?Use errors.Is(err, targetErr). This works even when the error has been wrapped, as long as the sentinel error is part of the error chain.
When should you use errors.As()?Use errors.As() when you need to extract a specific underlying error type and inspect its extra data or behavior, not just check whether it happened.
How do custom error types work in Go?You can define your own type and give it an Error() string method. This lets the type satisfy the error interface and carry extra information, such as a list of missing keys.
When should you use panic and recover?panic is for truly exceptional situations where the program cannot safely continue. recover is used inside a deferred function to catch a panic and prevent the program from exiting, but it should be used sparingly.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Go in Action, Second Edition ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Go in Action, Second Edition ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Go in Action, Second Edition ebook for free