Skip to content

Commit

Permalink
Add example code for error creation using Builder pattern
Browse files Browse the repository at this point in the history
  • Loading branch information
m-mizutani committed Oct 19, 2024
1 parent eaabdb0 commit 59a30b4
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
32 changes: 32 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,39 @@ Output:
}
```

### Builder

`goerr` provides `goerr.NewBuilder()` to create an error with pre-defined contextual variables. It is useful when you want to create an error with the same contextual variables in multiple places.

```go
type object struct {
id string
color string
}

func (o *object) Validate() error {
eb := goerr.NewBuilder().With("id", o.id)

if o.color == "" {
return eb.New("color is empty")
}

return nil
}

func main() {
obj := &object{id: "object-1"}

if err := obj.Validate(); err != nil {
slog.Default().Error("Validation error", "err", err)
}
}
```

Output:
```
2024/10/19 14:19:54 ERROR Validation error err.message="color is empty" err.values.id=object-1 (snip)
```

## License

Expand Down
30 changes: 30 additions & 0 deletions examples/builder/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package main

import (
"log/slog"

"github.com/m-mizutani/goerr"
)

type object struct {
id string
color string
}

func (o *object) Validate() error {
eb := goerr.NewBuilder().With("id", o.id)

if o.color == "" {
return eb.New("color is empty")
}

return nil
}

func main() {
obj := &object{id: "object-1"}

if err := obj.Validate(); err != nil {
slog.Default().Error("Validation error", "err", err)
}
}

0 comments on commit 59a30b4

Please sign in to comment.