JetbrainsDominika StankiewiczTutorial
How to Handle Errors in Go
Summary
Go treats errors as values rather than moving error handling outside normal control flow: functions return an error alongside other results, and callers check it. The guide presents the built-in error interface, returning errors with errors.New, wrapping failures with fmt.Errorf and %w, and distinguishing nil success from non-nil failure. It also explains panic and recover for unexpected failures, including deferred recovery in services that must continue handling other requests, while warning that panics should not replace ordinary error handling. Its best practices emphasize adding context, choosing informative custom error types, inspecting wrapped errors with errors.Is, errors.As, and errors.AsType, and logging errors when they are handled or cannot be returned. The conclusion recommends balancing early crashes with recovery when restarting is costly or when independent goroutines can continue safely.
Context
Go error handling differs from approaches in Java, C++, JavaScript, and Python because errors are values that remain part of normal program flow. Runtime failures can include logical, I/O, network, and data validation errors, each of which may require different handling.
Approach / What changed
The guide demonstrates returning errors alongside other values, creating errors with errors.New, wrapping them with fmt.Errorf and %w, checking them at the call site, and using panic, recover, deferred functions, custom error types, error inspection, logging, and selective recovery where appropriate.
Takeaways
Go conventionally returns an error as the rightmost result; callers typically assign it to err and handle it when it is non-nil.
fmt.Errorf with %w wraps an underlying error and provides an Unwrap method, while errors.Is, errors.As, and errors.AsType support inspection of error values.
log.Fatal calls os.Exit, which skips deferred functions; recovery can be preferable when uptime matters or other goroutines can continue independently.
Source and freshness
- Source
- blog.jetbrains.com
- Published
- Added to Yomu
- Last updated
Summaries are generated from the original by a language model. Check the original before relying on it.
Keep reading
Related reading
The Good Stuff
Paid picks we use ourselves. Links carry a referral code — a subscription through one earns us a commission at no extra cost to you.
The best engineering reads, once a week
One useful email. Unsubscribe anytime.