Skip to content

Commit

Permalink
feat: impl errorf method (#7)
Browse files Browse the repository at this point in the history
  • Loading branch information
abyssparanoia authored Nov 28, 2024
1 parent e162722 commit 61f2f67
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 0 deletions.
8 changes: 8 additions & 0 deletions errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,14 @@ func (x *Error) Wrap(cause error) *Error {
return err
}

// Errorf creates a new Error and copy message and id to new one. The error message is formatted by fmt.Sprintf.
func (x *Error) Errorf(format string, args ...any) *Error {
err := newError()
x.copy(err)
err.cause = fmt.Errorf(format, args...)
return err
}

// Values returns map of key and value that is set by With. All wrapped goerr.Error key and values will be merged. Key and values of wrapped error is overwritten by upper goerr.Error.
func (x *Error) Values() map[string]any {
var values map[string]any
Expand Down
34 changes: 34 additions & 0 deletions examples/zap/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package main

import (
"github.com/abyssparanoia/goerr"
"go.uber.org/zap"
)

var (
testErr = goerr.New("test error").
WithCategory("test_category").
WithCode("TEST123").
WithDetail("test detail").
WithValue("key", "value")
)

func main() {
l, _ := zap.NewDevelopment()
if err := wrapDoSomething(); err != nil {
l.Error("error", goerr.ZapError(err))
}
}

func wrapDoSomething() error {
if err := doSomething(); err != nil {
return err
}
return nil
}

func doSomething() error {
err := testErr.Errorf("failed to do something").
WithValue("other_key", "other_value")
return err
}
13 changes: 13 additions & 0 deletions zap.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package goerr

import (
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)

func ZapError(err error) zapcore.Field {
if goErr := Unwrap(err); goErr != nil {
return zap.Object("error", goErr)
}
return zap.Error(err)
}

0 comments on commit 61f2f67

Please sign in to comment.