Handle errors idiomatically in Go by checking the error return value immediately after a function call and returning or logging it if non-nil. This pattern ensures failures are caught early and propagated correctly up the call stack.
file, err := os.Open("data.txt")
if err != nil {
return fmt.Errorf("failed to open file: %w", err)
}
defer file.Close()
For specific error types like archive/tar.ErrInsecurePath, use errors.Is to check for the exact error and handle it accordingly:
hdr, err := tr.Next()
if err != nil {
if errors.Is(err, archive/tar.ErrInsecurePath) {
log.Println("skipping insecure path")
continue
}
return err
}
When wrapping errors, use fmt.Errorf with the %w verb to preserve the error chain for later inspection.