Error Wrapping and Inspection
Error Wrapping
Go wraps an error with context while preserving the original cause.
Error Wrapping
error_wrapping.go
package main
import (
"errors"
"fmt"
)
func main() {
var operation =
base := errors.New("config missing")
wrapped := fmt.Errorf("%s failed: %w", operation, base)
fmt.Println("operation=", operation)
fmt.Println("base=", base.Error())
fmt.Println("has_error=", wrapped != nil)
fmt.Println("message=", wrapped.Error())
}
package main
import (
"errors"
"fmt"
)
func main() {
var operation =
base := errors.New("config missing")
wrapped := fmt.Errorf("%s failed: %w", operation, base)
fmt.Println("operation=", operation)
fmt.Println("base=", base.Error())
fmt.Println("has_error=", wrapped != nil)
fmt.Println("message=", wrapped.Error())
}
package main
import (
"errors"
"fmt"
)
func main() {
var operation =
base := errors.New("config missing")
wrapped := fmt.Errorf("%s failed: %w", operation, base)
fmt.Println("operation=", operation)
fmt.Println("base=", base.Error())
fmt.Println("has_error=", wrapped != nil)
fmt.Println("message=", wrapped.Error())
}
wrapping
`fmt.Errorf` with `%w` adds context without discarding the error underneath.