🐹 Go (Golang) Intermediate

What is fmt.Errorf with %w and how do errors.Is / errors.As work?

Answer

Go 1.13 introduced error wrapping. fmt.Errorf("loading user: %w", err) wraps an existing error in a new one with additional context while preserving the original error in the chain. errors.Is(err, target) checks whether any error in the chain matches target (using == equality or the error's Is method) — useful for checking sentinel errors like sql.ErrNoRows. errors.As(err, &target) finds the first error in the chain that can be assigned to target's type, enabling access to fields on custom error types. Together they replace the fragile string-matching approach to error inspection.