The error type is a built-in type of Go language. When using it, you don't need to import it specifically. It is essentially an interface.
type error interface{ Error() string //Error() is an error message that needs to be filled in every customized error object. It can be understood as a field Error}
How to understand this customization?
We know that interface must have its implementation block before it can be called. Putting it here means that Error() must be filled in order to be used.
For example, the following three methods:
The first type:Customize errors through errors package
error := ("hello,error")//Use errors must import the "errors" packageif error != nil { (err) }
Let's explain the errors package, it is just a simple package filled with Error(). The content of the entire package has only one New method, you can directly view it
func New(text string) error
The second type:Customize through ()
err := ("hello error") if err != nil { (err) }
It can be said to be similar to the first one.
The third type:It is customized through custom MyError blocks
//A custom error type wrapped with an error type objecttype MyError struct { err error } //Customized Error()func (e MyError) Error() string { return () } func main() { err:=MyError{ ("hello error"), } (()) }
The three methods are not very different, and the output results are all hello error
In fact, error is just an error message. The actual throwing of exceptions is not simply based on error, panic and recover usages.
Supplement: Detailed explanation of go error interface and errors package
1 error interface
definition:
type error interface{ Error() string //Error() is a method, which is an error message that needs to be filled with each customized error object. It can be understood as a field Error}
1.1 Common calling methods
template
n, err := Foo(0) if err != nil { // Error handling} else { // Use the return value n}
Exercise 1
package main import ( "fmt" "os" ) func main() { f, err := ("/") if err != nil { (err) return } ((), "opened successfully") }
[root@localhost error]# go run
open /: no such file or directory
1.2 Custom error method
1.2.1 Function call error
func Foo(param int)(n int, err error) { // ... }
1.2.2 Custom Error Template 1
type fileError struct { } func (fe *fileError) Error() string { return "File Error" }
Exercise 1
Simulate an error
package main import "fmt" type fileError struct { } func (fe *fileError) Error() string { //Customization will overwrite the original Error interface return "File Error" } //Just just simulate an errorfunc openFile() ([]byte, error) { return nil, &fileError{} } func main() { conent, err := openFile() if err != nil { (err) } else { (string(conent)) } }
[root@localhost error]# go run
File Error
1.2 Custom Error Template 2
Add a string to customize
type fileError struct { s string } func (fe *fileError) Error() string { return }
Exercise 2
When declaring fileError, set the error text to be prompted
package main import "fmt" type fileError struct { s string } func (fe *fileError) Error() string { return } //Just just simulate an errorfunc openFile() ([]byte, error) { return nil, &fileError{"File Error, Custom"} } func main() { conent, err := openFile() if err != nil { (err) } else { (string(conent)) } }
[root@localhost error]# go run
File error, custom
Exercise 3
Add a time scale
package main import ( "fmt" "time" ) type MyError struct { When What string } func (e MyError) Error() string { return ("%v: %v", , ) } func oops() error { return MyError{ (1989, 3, 15, 22, 30, 0, 0, ), "the file system has gone away", } } func main() { if err := oops(); err != nil { (err) } }
[root@localhost error]# go run
1989-03-15 22:30:00 +0000 UTC: the file system has gone away
Exercise Three
No file opened error
package main import ( "fmt" "os" ) type PathError struct { Op string Path string Err error } func (e *PathError) Error() string { return + " " + + ": " + () } func main() { f, err := ("/") if errObject, ok := err.(*); ok { ("Error output:",err, "File Path:", ) return } ((), "opened successfully") }
[root@localhost error]# go run
Error output: open /: no such file or directory file path: /
2 errors package
2.1 Get the error package
go get /pkg/errors
2.2 ()
() Receive appropriate error message to create
Declare first and then use
Exercise 1
package main import ( "errors" "fmt" ) var errNotFound error = ("Not found error") func main() { ("error: %v", errNotFound) }
[root@localhost error]# go run
error: Not found error
Exercise 2
How to call err
Use directly
package main import ( "errors" "fmt" ) func Sqrt(f float64) (float64, error) { if f < 0 { return 0, ("math - square root of negative number") }else { return 1, ("math - square root of 10") } } func main() { if _, err := Sqrt(-1); err != nil { ("Error: %s\n", err) } }
[root@localhost error]# go run
Error: math - square root of negative number
3. Comparison of custom error with()
Comparing custom error and () functions have their own advantages according to their needs.
package main import ( "errors" "fmt" ) type MsgError struct { Code int Msg string } func (msg *MsgError) Error() string { return ("%s", ) } func f1(code int) (int, error) { if code == 1 { return -1, ("msg test error") } return code, nil } func f2(code int) (int, error) { if code == 1 { return -1, &MsgError{code, "struct msg test error"} } return code, nil } func main() { for _, v := range []int{1, 2, 3, 4, 5, 6} { if code, err := f1(v); err != nil { (err) } else { ("success:", code) } } for _, i := range []int{1, 2, 3} { if code, err := f2(i); err != nil { (err) } else { ("success:", code) } } }
[root@localhost error]# go run msg test error success: 2 success: 3 success: 4 success: 5 success: 6 struct msg test error success: 2 success: 3
The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.