Chapter 9. Errors
Error handling is one of the biggest challenges for developers moving to Go from other languages. For those used to exceptions, Go’s approach feels anachronistic. But solid software engineering principles underlie Go’s approach. In this chapter, you’ll learn how to work with errors in Go. You’ll also take a look at panic and recover, Go’s system for handling errors that should stop execution.
How to Handle Errors: The Basics
As was covered briefly in Chapter 5, Go handles errors by returning a value of type error as the last return value for a function. This is entirely by convention, but it is such a strong convention that it should never be breached. When a function executes as expected, nil is returned for the error parameter. If something goes wrong, an error value is returned instead. The calling function then checks the error return value by comparing it to nil, handling the error, or returning an error of its own. A simple function with error handling looks like this:
funccalcRemainderAndMod(numerator,denominatorint)(int,int,error){ifdenominator==0{return0,0,errors.New("denominator is 0")}returnnumerator/denominator,numerator%denominator,nil}
A new error is created from a string by calling the New function in the errors package. Error messages should not be capitalized nor should they end with punctuation or a newline. In most cases, you should set the other return values to their zero values when a non-nil error is returned. ...