The error Interface
Returning and checking errors idiomatically
Go's Error Philosophy
Go handles errors as values, not exceptions. Functions return an error as the last return value. The caller must check it explicitly:
package main
import ("fmt"; "strconv")
func main() {
n, err := strconv.Atoi("abc")
if err != nil {
fmt.Println("error:", err) // handle it
return
}
fmt.Println(n)
}The error Interface
The built-in error is a simple interface:
// Built into Go — no import needed
type error interface {
Error() string
}
// Any type with Error() string satisfies it
// nil means no errorAll lessons in this course
- The error Interface
- Creating Custom Errors
- Error Wrapping and Unwrapping
- panic, recover and defer