A Go error reports that an operation did not complete as expected. It is a value for the caller to check, not an exception that Go handles automatically. When the caller can respond or pass the failure upward, return an error. Reserve a panic for a condition in which the program or immediate subsystem cannot continue. section 4.0 section 4.3.1
Return and check an error
This complete program rejects an empty input list and otherwise joins the supplied words: package main import ( "errors" "fmt" "os" "strings" ) func Concat(parts ...string) (string, error) { if len(parts) == 0 { return "", errors.New("no strings supplied") } return strings.Join(parts, " "), nil } func main() { result, err := Concat(os.Args[1:]...) if err != nil { fmt.Println("Error:", err) return } fmt.Println(result) } The error is the last return value. A nil error means the caller can use the result; a non-nil error explains why the operation failed. Here, the empty string alone cannot distinguish failure from a valid result, so discarding the error would lose information. section 4.1 section 4.1.1
Choose how much detail the caller needs:
- Use an ordinary error message when no structured information would change the caller’s response. Document what other values the function returns on failure. section 4.1.1
- Define a custom type implementing Error() string when callers need fields or must distinguish kinds of failure. A parser error can retain a message, line, and character position. section 4.1.2
- At an HTTP boundary, communicate failure with a status code and message. A client can inspect the status, turn an unexpected response into an error, and use status information to decide whether retrying makes sense. section 11.2 section 11.2.2
Checking before an operation can keep a failure in the ordinary error path: a division function can return an error for a zero divisor rather than trigger a divide-by-zero panic. An unhandled panic unwinds the stack and stops the program. When recovery is appropriate, a deferred function can call recover; passing an error to panic makes the recovered value easier to handle as an error. section 4.3.1 section 4.3.2 section 4.3.4











