From 59a30b4a6d9be7446136db9477963c12971c4fd8 Mon Sep 17 00:00:00 2001 From: Masayoshi Mizutani Date: Sat, 19 Oct 2024 14:21:40 +0900 Subject: [PATCH] Add example code for error creation using Builder pattern --- README.md | 32 ++++++++++++++++++++++++++++++++ examples/builder/main.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 examples/builder/main.go diff --git a/README.md b/README.md index 642ae79..b3e738c 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/examples/builder/main.go b/examples/builder/main.go new file mode 100644 index 0000000..b289a10 --- /dev/null +++ b/examples/builder/main.go @@ -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) + } +}