Skip to content

Commit 2e21ac3

Browse files
author
Dean Karn
committed
Add LookupTag function
1 parent 05c4e17 commit 2e21ac3

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

errors.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,3 +75,24 @@ func HasType(err error, typ string) bool {
7575
}
7676
return false
7777
}
78+
79+
// LookupTag recursively searches for the provided tag and returns it's value or nil
80+
func LookupTag(err error, key string) interface{} {
81+
switch t := err.(type) {
82+
case Chain:
83+
for i := len(t) - 1; i >= 0; i-- {
84+
for j := 0; j < len(t[i].Tags); j++ {
85+
if t[i].Tags[j].Key == key {
86+
return t[i].Tags[j].Value
87+
}
88+
}
89+
}
90+
case *Link:
91+
for i := 0; i < len(t.Tags); i++ {
92+
if t.Tags[i].Key == key {
93+
return t.Tags[i].Value
94+
}
95+
}
96+
}
97+
return nil
98+
}

errors_test.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ func TestCause(t *testing.T) {
104104
}
105105
}
106106

107-
func TestIsErr(t *testing.T) {
107+
func TestCause2(t *testing.T) {
108108
err := Wrap(io.EOF, "prefix")
109109
err = Wrap(err, "prefix2")
110110

@@ -132,3 +132,10 @@ func TestHelpers(t *testing.T) {
132132
t.Errorf("Expected to have type 'Test'")
133133
}
134134
}
135+
136+
func TestLookupTag(t *testing.T) {
137+
err := Wrap(io.EOF, "prefix").WithTag("Key", "Value")
138+
if LookupTag(err, "Key").(string) != "Value" {
139+
t.Fatalf("want %s got %v", "Value", LookupTag(err, "Key"))
140+
}
141+
}

0 commit comments

Comments
 (0)