Skip to content

Commit

Permalink
Update errors coding style
Browse files Browse the repository at this point in the history
The `github.com/pkg/errors` package is deprecated and archived. Update
the style guide to follow Go standard style for `error` type wrapping.

Signed-off-by: SuperQ <[email protected]>
  • Loading branch information
SuperQ committed Jun 25, 2024
1 parent d82b2bd commit d8635bd
Showing 1 changed file with 9 additions and 6 deletions.
15 changes: 9 additions & 6 deletions docs/contributing/coding-style-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -692,13 +692,16 @@ for _, elem := range elems {
</td></tr>
</tbody></table>

#### Wrap Errors for More Context; Don't Repeat "failed ..." There.
#### Wrap Errors for More Context

We use [`pkg/errors`](https://github.com/pkg/errors) package for `errors`. We prefer it over standard wrapping with `fmt.Errorf` + `%w`, as `errors.Wrap` is explicit. It's easy to by accident replace `%w` with `%v` or to add extra inconsistent characters to the string.
We use [`fmt.Errorf`](https://pkg.go.dev/fmt#Errorf) package for `errors`.

Use [`pkg/errors.Wrap`](https://github.com/pkg/errors) to wrap errors for future context when errors occur. It's recommended to add more interesting variables to add context using `errors.Wrapf`, e.g. file names, IDs or things that fail, etc.
Export package error variables with [`errors.New()`](https://pkg.go.dev/errors#New) so that they can be used with [`errors.Is`](https://pkg.go.dev/errors#Is). For example, if you want package users to be able to handle errors.

NOTE: never prefix wrap messages with wording like `failed ... ` or `error occurred while...`. Just describe what we wanted to do when the failure occurred. Those prefixes are just noise. We are wrapping error, so it's obvious that some error occurred, right? (: Improve readability and consider avoiding those.
Example:
```go
var ErrNoSuchHost = errors.New("no such host")
```

<table>
<tbody>
Expand All @@ -707,7 +710,7 @@ NOTE: never prefix wrap messages with wording like `failed ... ` or `error occur

```go
if err != nil {
return fmt.Errorf("error while reading from file %s: %w", f.Name, err)
return err
}
```

Expand All @@ -717,7 +720,7 @@ if err != nil {

```go
if err != nil {
return errors.Wrapf(err, "read file %s", f.Name)
return fmt.Errorf("error while reading from file %s: %w", f.Name, err)
}
```

Expand Down

0 comments on commit d8635bd

Please sign in to comment.