Golang & Concurrency (50 Qs)•Part 1: Go Language Core, Memory & Runtime Internals (1 - 15)
How does Error Handling work in Go: Idiomatic Errors, `errors.Is()`, `errors.As()`, and Wrapping?
senior LevelCode ExamplegolangGo Language Core
In Simple Words:
Go rejects exceptions (try-catch) in favor of explicit error returns as values: val, err := doWork().
In Go 1.13+:
- Wrapping: Wrap an error with context using
fmt.Errorf("failed to fetch user: %w", err). The%wverb embeds the original error. errors.Is(err, target): Unwraps an error tree to check if a specific sentinel error (e.g.sql.ErrNoRows) is present anywhere in the chain.errors.As(err, &targetStruct): Checks if any error in the chain matches a specific custom error type and binds it.
go
var ErrNotFound = errors.New("resource not found")
func findUser(id string) error {
return fmt.Errorf("database query failed: %w", ErrNotFound)
}
func main() {
err := findUser("123")
if errors.Is(err, ErrNotFound) {
// Accurately detected sentinel error through wrapping chain!
}
}