This is a creation in Article, where the information may have evolved or changed.
Error handling is an important topic to consider in any programming language.
Error interface
The go language introduces a standard pattern for error handling, the errors interface, which is defined as follows:
Typeerrorinterface{
Error()string
}
for most functions, if you want to return an error, you can roughly define it as the following pattern, with error as the last of several return values, but this is not a mandatory requirement:
FuncFoo (paramint)(nint) ,err error) {
//
}
the code at the time of invocation recommends handling error conditions as follows:
n,err: =Foo(0)
Iferr! =null {
// error Handling
}Else{
//Use return value n
}
below we use the actual code in the Go library to demonstrate how to use the custom error type.
First, define a type that is used to host the error message. Because of the flexibility of the interface in the go language, we do not need to inherit from the error interface or, like Java, need to use implements to explicitly specify the relationship between the type and interface, as follows:
Typepatherrorstruct{
Opstring
Pathstring
Errerror
}
If so, how can the compiler know that Patherror can be passed as an error? The key is that the following code implements the error () method
Func(e*patherror)Error ( ) string{
return e. Op + " " + E. Path + ":" + e. ERR. Error()
}
Defer
Keyword defer is a very interesting feature of the Go language introduction.
Panic () and recover ()
The go language introduces two built-in functions panic () and recover () to report and handle run-time errors and error scenarios in the program