Go error handling, wrapping with errors.Is and As, panic and recover, go test, benchmarks, go modules and tooling.
42 cards · basic cards · AI-written, checked twice. Edit anything.
- What methods must a type implement to satisfy the error interface?
Show answer
A single Error() method that returns a string
- How do you create a simple error using the errors package?
Show answer
errors.New("error message")
- How do you wrap an error to preserve it for errors.Is and errors.As?
Show answer
fmt.Errorf("context: %w", err)
- What does errors.Is check?
Show answer
Whether an error in the chain matches a target error value
- What does errors.As do?
Show answer
Unwraps an error chain and assigns the first matching type to a variable
- What does errors.Unwrap return?
Show answer
The error wrapped by %w in the argument, or nil if not wrapped
- What is a sentinel error?
Show answer
A predefined error variable (like var ErrNotFound = errors.New("not found")) used for comparison with errors.Is
- How do you create a custom error type?
Show answer
Define a type with an Error() method that returns a string
- When should you wrap an error versus returning it unwrapped?
Show answer
Wrap it to add context; return unwrapped at API boundaries where wrapping adds no value
- Name one scenario where panic is appropriate in Go.
Show answer
Programmer error or internal invariant violation (not user input or recoverable failures)
- Should invalid user input cause a panic or return an error?
Show answer
Return an error (panic is for unrecoverable programmer errors)
- What does recover() do?
Show answer
Stops a panic and returns the value passed to panic, or nil if not panicking
- Where must you call recover() for it to work?
Show answer
Inside a defer statement
- Can recover() in one goroutine catch a panic from a different goroutine?
Show answer
No, recover only catches panics in the same goroutine
- What does the go test command do?
Show answer
Runs all *_test.go files in the current package and reports results