User Tools

Site Tools


go:errors:error_wrapping

This is an old revision of the document!


Error wrapping (%w)

What is it?

Error wrapping means adding context to an error while keeping the original error inside it.

In Go, `fmt.Errorf` supports wrapping using `%w`:

fmt.Errorf("doing X: %w", err)

What is it used for?

  • Add helpful context at each layer (repo → usecase → handler).
  • Preserve the root cause so callers can detect it with `errors.Is/As`.

Example

if err := dbCall(); err != nil {
    return fmt.Errorf("update user: %w", err)
}

Notes / pitfalls

  • Use `%w` only once in a single `fmt.Errorf` call.
  • Use `%v` if you only want formatting without wrapping.
  • Wrapping enables `errors.Is` and `errors.As` to work through layers.

Hard words (English)

  • wrap /ræp/: bọc
  • preserve /prɪˈzɝːv/: giữ lại
  • root cause /ruːt kɔːz/: nguyên nhân gốc
  • layer /ˈleɪər/: tầng
go/errors/error_wrapping.1767655060.txt.gz · Last modified: by phong2018