The go language introduces a standard model for error handling, the error interface, which is defined as follows:
Type Error Interface {
Error () string
}
For most functions, if you want to return an error, you can generally define it as the following pattern, which returns the error as a variety of
The last of the values, but this is not a mandatory requirement:
Func Foo (param int) (n int, err error) {
// ...
}
The code at the time of the call suggests that the error condition be handled as follows:
N, Err: = Foo (0)
If Err!= nil {
Error handling
} else {
Use return value n
} Custom Error
Package main
Import (
"FMT"
"Time"
)
//Define an error structure body to load error message
type myerror struct {
when Time. Time
What string
}
//Implementation Error Interface Error () method
func (e *myerror) error () string {return
FMT. Sprintf ("At%v,%s",
E.when, E.what)
}
//Defines a method, note that the return value type contains an error
func run () error {
returns &myerror{time
. Now (),
"It didn ' t work",
}
func main () {
If err: = run (); Err!= Nil {
//because the run () method returns an ER Ror the value of the Err parameter is the return value of the error () method and a string string
fmt. PRINTLN (Err)
}
}