Go function error handling debugging skills include: 1. Use fmt.Println() to print error information; 2. Use errors.Unwrap() to unwrap nested errors; 3. Use log.Printf() to record error information; 4 . Create custom error types to provide detailed error information; 5. Use assertions to check errors at runtime.
Debugging Tips in Go Function Error Handling
Error handling in Go is very powerful, but sometimes debugging errors is very difficult . This article will introduce some techniques to help you find and fix errors in functions.
1. Use fmt.Println()
The easiest way is to use fmt.Println()
to print error message. This is useful for quick debugging, but should not be done in production code.
package main import ( "fmt" "os" ) func main() { f, err := os.Open("file.txt") if err != nil { fmt.Println(err) os.Exit(1) } // ... }
2. Use errors.Unwrap()
##errors.Unwrap() can help you unwrap set of errors. For example, if a function throws an
os.ErrNotExist error, you can use
errors.Unwrap() in the surrounding function to get the underlying error, which is
nil.
package main import ( "errors" "fmt" "os" ) func main() { f, err := os.Open("file.txt") if err != nil { if errors.Unwrap(err) == os.ErrNotExist { fmt.Println("file does not exist") } else { fmt.Println(err) } os.Exit(1) } // ... }
3. Use log.Printf()
log.Printf() is a more advanced log Logging function can write error information to a file or console. This is useful for debugging in production code.
package main import ( "fmt" "log" "os" ) func main() { f, err := os.Open("file.txt") if err != nil { log.Printf("failed to open file: %v", err) os.Exit(1) } // ... }
4. Use custom error types
Custom error types can provide more information about errors. For example, you can define aFileNotFoundError type to indicate that the file does not exist.
package main import ( "errors" "fmt" "os" ) type FileNotFoundError struct { path string } func (e FileNotFoundError) Error() string { return fmt.Sprintf("file not found: %s", e.path) } func main() { f, err := os.Open("file.txt") if err != nil { if errors.Is(err, FileNotFoundError{}) { fmt.Println("file does not exist") } else { fmt.Println(err) } os.Exit(1) } // ... }
5. Use assertions
Assertions can help you check for errors at runtime and trigger a panic when an error occurs.package main import ( "fmt" "io/ioutil" "os" ) func main() { data, err := ioutil.ReadFile("file.txt") if err != nil { fmt.Println(err) os.Exit(1) } // 将错误包装成 panic if len(data) == 0 { panic("empty file") } // ... }
The above is the detailed content of Debugging skills in golang function error handling. For more information, please follow other related articles on the PHP Chinese website!