Error handling tips in Golang functions: Use error.Error() to convert errors to strings. Use Printf to format error messages. Use wrap to add an error summary. Define custom error types to catch duplicate errors. Use the wrap function to handle errors in API responses.
Error handling skills in Golang functions
The Go language provides a rich error handling mechanism that can help us write robust , reliable code. This article will cover different techniques for handling errors in Golang functions, along with examples.
error.Error()
The easiest way is to use error.Error()
to convert the error message into a string.
func f() error { return errors.New("some error") } func main() { err := f() if err != nil { fmt.Println(err.Error()) // 输出: some error } }
Printf
For more complex errors, we can use Printf
to format the error message.
func f() error { return fmt.Errorf("cannot open file: %s", filename) } func main() { err := f() if err != nil { fmt.Println("Error:", err) // 输出: Error: cannot open file: filename } }
wrap
wrap
function adds a layer of summary on top of existing errors.
func f() error { err := os.OpenFile("filename", os.O_RDWR, 0666) // 可能抛出错误 return errors.Wrap(err, "failed to open file") } func main() { err := f() if err != nil { fmt.Println("Error:", err) // 输出: Error: failed to open file: filename // 同时包含底层错误信息 } }
Custom error types
For recurring errors, we can define custom error types.
type FileOpenError struct { path string err error } func (e *FileOpenError) Error() string { return fmt.Sprintf("cannot open file: %s: %v", e.path, e.err) } func f() error { err := os.OpenFile("filename", os.O_RDWR, 0666) if err != nil { return &FileOpenError{path: "filename", err: err} } return nil } func main() { err := f() if err != nil { if casted, ok := err.(*FileOpenError); ok { fmt.Println("Error:", casted.Error()) // 输出: cannot open file: filename: open filename: permission denied } } }
Practical case
The following is an API response example using the wrap
function to handle errors:
func apiCall() error { resp, err := http.Get("https://example.com/api") if err != nil { return errors.Wrap(err, "failed to make API call") } defer resp.Body.Close() ... // 处理响应 } func main() { err := apiCall() if err != nil { fmt.Println("Error:", err) // 输出: Error: failed to make API call: Get https://example.com/api: dial tcp: lookup example.com on 8.8.8.8:53: no such host } }
By using these With error handling techniques, we can ensure that Golang functions report errors in a clear, actionable way.
The above is the detailed content of Error handling skills in golang functions. For more information, please follow other related articles on the PHP Chinese website!