Skip to content

Commit

Permalink
restored the error message template
Browse files Browse the repository at this point in the history
  • Loading branch information
hedzr committed Feb 24, 2022
1 parent dc949cf commit 93bd749
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 3 deletions.
21 changes: 18 additions & 3 deletions causes.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,13 @@ import (

type causes2 struct {
Code
Causers []error
msg string

Causers []error
msg string

unwrapIndex int

liveArgs []interface{} // error message template ?
}

// WithCode for error interface
Expand Down Expand Up @@ -73,11 +77,22 @@ func (w *causes2) Attach(errs ...error) {
_ = w.WithErrors(errs...)
}

// FormatWith _
func (w *WithStackInfo) FormatWith(args ...interface{}) {
w.liveArgs = args
}

func (w *causes2) Error() string {
var buf bytes.Buffer
if w.msg != "" {
buf.WriteString(w.msg)
if len(w.liveArgs) > 0 {
msg := fmt.Sprintf(w.msg, w.liveArgs...)
buf.WriteString(msg)
} else {
buf.WriteString(w.msg)
}
}

var needclose, needsep bool
if w.Code != OK {
if buf.Len() > 0 {
Expand Down
16 changes: 16 additions & 0 deletions def.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,22 @@ type Buildable interface {

// Container _
Container

// FormatWith adds live args for formatting the message template.
//
// While you New an Error with format template without supplying
// the args at same time, you'll create an error message template.
// You could feed the live args later.
// A sample is:
//
// err := errors.New("template here: %v")
// // ...
// err.FormatWith("good day")
// println(err) // got: template here: good day
// err.FormatWith("bye")
// println(err) // got: template here: bye
//
FormatWith(args ...interface{})
}

type causer interface {
Expand Down
12 changes: 12 additions & 0 deletions errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ func TestUnwrap(t *testing.T) {
t.Logf("failed: %v", e)
}
}

func TestWithStackInfo_New(t *testing.T) {

err := New("hello %v", "world")
Expand All @@ -103,3 +104,14 @@ func TestWithStackInfo_New(t *testing.T) {
t.Logf("Data: %v", err2.Data())
t.Logf("TaggedData: %v", err2.TaggedData())
}

func TestTemplateFormat(t *testing.T) {
err := New("cannot set: %v (%v) -> %v (%v)")

err.FormatWith("a", "b", "c", "d")
t.Logf("Error: %v", err)
t.Logf("Error: %+v", err)

err.FormatWith("1", "2", "3", "4")
t.Logf("Error: %v", err)
}

0 comments on commit 93bd749

Please sign in to comment.