乐闻世界logo
搜索文章和话题

How do you use the "errors" package to create and manipulate errors in Go?

1个答案

1

In Go, the errors package is a fundamental and practical tool for creating and handling errors. It provides basic yet sufficiently powerful utilities for error management. Here are some steps and examples for creating and manipulating errors using the errors package:

1. Creating a Simple Error

To create a new error, you can use the errors.New function. This function accepts a string parameter as the error message and returns an error object.

go
import ( "errors" "fmt" ) func main() { err := errors.New("This is an error message") if err != nil { fmt.Println(err) } }

2. Creating Formatted Errors with fmt.Errorf

If you need to include variables or more complex formatting in the error message, use fmt.Errorf. It operates similarly to fmt.Sprintf, but returns an error object.

go
func validateAge(age int) error { if age < 18 { return fmt.Errorf("age %d is below 18, which is not acceptable", age) } return nil } func main() { err := validateAge(16) if err != nil { fmt.Println(err) } }

3. Error Wrapping

Go 1.13 introduced error wrapping, allowing you to "wrap" an error to add contextual information while preserving the original error's type and content. Use the %w placeholder to achieve this.

go
func readFile(filename string) error { _, err := os.ReadFile(filename) if err != nil { return fmt.Errorf("error reading file '%s': %w", filename, err) } return nil } func main() { err := readFile("non-existent-file.txt") if err != nil { fmt.Println(err) // Use errors.Unwrap to access the original error if originalErr := errors.Unwrap(err); originalErr != nil { fmt.Println("Original error:", originalErr) } } }

4. Checking Specific Errors

When you need to make different handling decisions based on error type or content, use errors.Is and errors.As.

go
var ErrNetworkTimeout = errors.New("network timeout") func performRequest() error { // Simulate a network request error return fmt.Errorf("request error: %w", ErrNetworkTimeout) } func main() { err := performRequest() if errors.Is(err, ErrNetworkTimeout) { fmt.Println("Network timeout detected; consider retrying") } else { fmt.Println("Other error occurred") } }

In interviews, providing concrete examples to demonstrate your approach to using tools or methods is highly valued. Through these steps and examples, I illustrated how to create and manipulate errors in Go programs, which is a critical aspect of development for ensuring program robustness and maintainability.

2024年8月9日 03:08 回复

你的答案