skip to content
Alvin Lucillo

Wrapped errors

/ 1 min read

💻 Tech

Formatting directive %w allows us to wrap errors so we can unwrap/check it later. This helps with ensuring we preserve the original error while allowing additional information to the error.

func main() {
	originalErr := errors.New("original error")
	wrappedErr := fmt.Errorf("additional context: %w", originalErr)

	fmt.Println(wrappedErr) // Output: additional context: original error

	unwrappedErr := errors.Unwrap(wrappedErr)
	fmt.Println(unwrappedErr) // Output: original error
}