Best Practice: Always return an error, even if no error is detected, for the caller to respond to. Use Sentinel error values to represent specific types of errors and enhance readability. Use wrapped errors to enhance the original error message for easier debugging. Use defer to ensure resources are released even if a panic or error occurs. Practical case: CalculateAverage function returns the average value or error: if the array is empty, ErrNoNumbers error is returned. If the array contains negative numbers, a formatted error is returned. Otherwise, the average value is returned.
In the Go language, error handling is an important task, which can help us elegantly Handle errors and avoid unexpected behavior. Here are some best practices in function error handling:
1. Always return an error
Functions should always return an error, even if they don't detect any error. This will allow the caller to respond based on the actual situation. For example:
func ParseJSON(input []byte) (map[string]interface{}, error) { var data map[string]interface{} if err := json.Unmarshal(input, &data); err != nil { return nil, err } return data, nil }
2. Using Sentinel error values
Sentinel error values are special values that can be used to represent specific types of errors. This can make error handling more concise and readable. For example:
var ErrInputTooLong = errors.New("input is too long")
3. Using wrapped errors
Using wrapped errors can enhance the original error message by adding additional contextual information. This can help with debugging and understanding the root cause of the error. For example:
func OpenFile(path string) (*os.File, error) { file, err := os.Open(path) if err != nil { return nil, fmt.Errorf("failed to open file %s: %w", path, err) } return file, nil }
4. Using defer
defer
statement can be used to ensure that resources are released even in the event of a panic or error. This is critical for closing files, freeing memory, etc. For example:
file, err := os.Open("data.txt") if err != nil { return nil, err } defer file.Close()
Practical case:
Let’s look at a practical case using these best practices:
func CalculateAverage(numbers []int) (float64, error) { if len(numbers) == 0 { return 0, ErrNoNumbers } sum := 0 for _, number := range numbers { if number < 0 { return 0, fmt.Errorf("invalid number %d: must be non-negative", number) } sum += number } return float64(sum) / float64(len(numbers)), nil } // 主函数 func main() { numbers := []int{1, 2, 3, 4, 5} average, err := CalculateAverage(numbers) if err != nil { fmt.Println("Error:", err) } else { fmt.Println("Average:", average) } }
By following these best practices With practice, we can ensure that function error handling is both robust and maintainable.
The above is the detailed content of Best practices in golang function error handling. For more information, please follow other related articles on the PHP Chinese website!