Skip to content

Commit 322321d

Browse files
committed
add Strace
1 parent 51ea6b8 commit 322321d

File tree

2 files changed

+29
-4
lines changed

2 files changed

+29
-4
lines changed

gen/errorStruct.tmpl

+4
Original file line numberDiff line numberDiff line change
@@ -70,3 +70,7 @@ func (e *{{ .ErrName }}) AddError(err error) grr.Error {
7070
func (e *{{ .ErrName }}) Trace() {
7171
grr.Trace(e)
7272
}
73+
74+
func (e *{{ .ErrName }}) Strace() string {
75+
return grr.Strace(e)
76+
}

grr/grr.go

+25-4
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ type Error interface {
1818
AddError(err error) Error
1919
GetTraits() map[Trait]any
2020
Trace()
21+
Strace() string
2122
}
2223

2324
// grrError implements the Error interface
@@ -99,10 +100,6 @@ func Strace(err error) string {
99100
return err.Error()
100101
}
101102

102-
// trace like so:
103-
// an error occured; op: SomeOp
104-
// |- the next level error
105-
// |- the next level error
106103
var errs []error
107104

108105
for {
@@ -165,6 +162,30 @@ func AsGrr(e Error, err error) (Error, bool) {
165162
}
166163
}
167164

165+
// Gets the trait value of the **innermost** grr.Error in the chain
166+
// This let's you assign a trait to the root error and have it propogate down the stack
167+
func GetTrait(err error, key Trait) (any, bool) {
168+
if !IsGrr(err) {
169+
return nil, false
170+
}
171+
172+
bottomGrr := UnwrapAllGrr(err.(Error))
173+
174+
return bottomGrr.GetTrait(key)
175+
}
176+
177+
// Unwraps to the bottom-most grr.Error in the chain. This is the closest grr.Error to the root error
178+
func UnwrapAllGrr(err Error) Error {
179+
for {
180+
if casted, ok := err.Unwrap().(Error); ok {
181+
err = casted
182+
continue
183+
}
184+
185+
return err
186+
}
187+
}
188+
168189
func UnwrapAll(e Error) error {
169190
last := e.Unwrap()
170191

0 commit comments

Comments
 (0)