liveBook · Manning

Error transformation

As explained in 100 Go Mistakes and How to Avoid Them

Error transformation is the conversion of an error into another error without preserving the original error for unwrapping.

Error transformation converts an error into another error without preserving the original for unwrapping. Use it when exposing the source error would create unwanted coupling. section 7.2

Choose the handling strategy according to what callers should access:

  • Return the error directly when no additional context or classification is needed. section 7.2
  • Wrap with fmt.Errorf("bar failed: %w", err) when callers should retain access to the source error. section 7.2
  • Transform with fmt.Errorf("bar failed: %v", err) when adding context without making the source error available. section 7.2

Preventing error unwrapping

if err != nil { return fmt.Errorf("bar failed: %v", err) } The resulting message retains the context and text but does not expose the original error for unwrapping. section 7.2

Figure 7.7 Converting the error

Use the error-conversion figure to compare transformed errors with wrapped errors. section 7.2

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Contrasts direct returns, custom error types, %w wrapping, and %v transformation through examples and a comparison table.
Examples
Uses direct return, BarError construction, %w wrapping, and %v transformation examples.
What it assumes
Assumes familiarity with returned errors and distinguishes added context from error classification.
What you can do after
Apply it via fmt.Errorf with %v when contextualizing an error without preserving it for unwrapping.
How it connects
Connects error transformation with error wrapping, custom error types, error context, and caller access to source errors.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.