This is the sixth day of my participation in Gwen Challenge
In Go, errors are expected. Let the caller decide what to do by returning the error method to the caller.
There are three ways to handle errors: Error, Deferred, and Panic
The error interface
Built-in Error interface
Go language built-in error interface, in only one error method, return an error message
type error interface{
ERROR() string
}
// demo
i,err := strconv.Atoi("a")
Copy the code
The strconv.atoi () function is a string to an integer. In demo, a cannot be converted to an int. This will result in an error and the second return value.
Errors. New User-defined error information
Errors. New(” Custom error message “) generates an error message back to the caller
Custom error
When errors.New is used to pass only one string and only the string type, you can use custom error to meet your requirements
Custom error structure, error interface
type errReturn struct{
code int
msg string
}
func (errR errReturn) Error() string{
return errR.errorMsg
}
Copy the code
Nested error
Nested error
The Error Wrapping function is added in Go 1.13, which can generate a new Error based on an existing Error and retain the information of the original Error
E :=errors.New(" error: %w") w:= Errorf(" error: %w",e) FMT.Println(w)Copy the code
Untangle nested errors
Nested errors can also be unwrapped by using the errors.Unwrap function
errors.Unwrap(w)
Copy the code
Error function judgment and conversion
- Errors. Is: checks whether the error Is the same
- Errors. As function: overwrite
Deferred function
The defer keyword is used to modify a function or method so that it will not be executed until it returns, deferred but executed
Common scenarios are paired operations, such as opening and closing files, locking and releasing locks, establishing and releasing connections
Abnormal panic
Go is a statically strongly typed language, and many errors are caught at compile time as much as possible, but some problems that occur at run time can cause panic exceptions
Panic exceptions cause programs to break and crash, so use error instead of Panic for normal errors
Panic is a built-in function of Go that accepts arguments of type interface{}, meaning that any type can be used as an argument to Panic
func panic(v interface{})
Copy the code
Recover catches panic exceptions
If the program stops during a Panic exception, but sometimes some resources need to be released before the program crashes, you need to recover during a Panic exception before processing.
The recover function recovers the panic exception
Use: defer+ anonymous function +recover function. The recover function returns the same values as the parameters passed through panic
func main(a){
defer func(a){
if p:=recover(a); p! =nil{
fmt.Println(p)
}
}()
// ...
}
Copy the code