Wrapping with %w in Go
fmt.Errorf with %w adds context and keeps the original reachable.
var ErrNotFound = errors.New("not found")
func loadTour(slug string) error {
if slug == "" {
return fmt.Errorf("load tour: %w", ErrNotFound)
}
return nil
}
func handler(slug string) string {
err := loadTour(slug)
if err == nil {
return "loaded"
}
wrapped := fmt.Errorf("handler: %w", err)
return fmt.Sprintf("%v | inner=%v", wrapped, errors.Unwrap(wrapped))
}
How it works
%wrecords the wrapped error;%vonly formats it.- Each layer adds what it knows, not a whole traceback.
errors.Unwrappeels one layer back off.
Keywords and builtins used here
errorfuncifreturnstringvar
The run, in numbers
- Lines
- 17
- Characters to type
- 361
- Tokens
- 84
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 50 seconds.
Step 1 of 4 in Wrapping, step 4 of 15 in Errors.