In languages such as Python, Java, and JavaScript, exception handling commonly means throwing and catching exception objects. Go handles ordinary failures differently: a function returns an error, usually as its last return value. Check that error before using the result. A panic is separate; it signals a severe condition rather than an ordinary task failure. section 4.1 section 4.0
Listing 4.1 Returning an error
package main
import (
"errors" #1
"strings"
)
func Concat(parts ...string) (string, error) { #2
if len(parts) == 0 {
return "", errors.New("No strings supplied") #3
} #3
return strings.Join(parts, " "), nil #4
}
The Concat listing shows the return-value pattern: no input produces an empty string and an error; successful input produces the joined string and nil. section 4.1
Handle the returned values according to what the caller needs:
- Test err != nil. Handle the failure locally or return the error to a caller that can decide what to do. section 4.1 section 4.0
- Do not mistake a returned value for proof of success. An empty string, for example, may be a valid result or may accompany an error; document what a function returns on failure. section 4.1.1
- Use errors.New for a simple error or fmt.Errorf for a formatted message. Custom error types can give callers more information for their next decision. section 4.1.1 section 4.4
Treat an HTTP response as an error when appropriate
A successful HTTP request can still return an unexpected status. A request wrapper can check the status code and content type, convert a custom JSON error response into a Go error, and return it to the caller. An Error method lets a custom response type satisfy the error interface. section 11.2.2
Use errors for failures a caller may handle or recover from. Reserve panics for severe conditions; when goroutines are involved, responding to a panic also matters for avoiding crashes or deadlocks. section 4.0 section 4.4
























