Go Context: Not Checking Err After Long Ops
In this tutorial, you'll learn about Go Context: Not Checking Err After Long Ops. We cover key concepts, practical examples, and best practices.
Context error checking -- Check ctx.Err() after long operations to detect cancellation and abort early.
The Problem
After a long-running operation, check if the context was cancelled before using the result. This prevents wasted work on cancelled requests.
Wrong
func fetchUser(ctx context.Context, id int) (*User, error) {
data, _ := db.Query(ctx, "SELECT ...")
return processResult(data), nil // Context may be cancelled!
}
Output:
// Even if context cancelled, processResult runs with data
Right
func fetchUser(ctx context.Context, id int) (*User, error) {
data, err := db.QueryContext(ctx, "SELECT ...")
if err != nil { return nil, err }
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
return processResult(data), nil
}
}
Output:
// If cancelled, error returned immediately. No wasted work.
Prevention
- Check ctx.Err() after long operations
- Use select with default to check non-blocking
- Return ctx.Err() for cancellation info
- DB/SQL/HTTP clients already check context internally
- Log cancelled operations for debugging
Common Mistakes with context err check
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro