Skip to content

Commit 0a053a0

Browse files
authored
Merge pull request #7 from bboreham/fewer-panics
On panic while printing, attempt to print panic value
2 parents c2152ce + 5e20bc1 commit 0a053a0

File tree

2 files changed

+21
-3
lines changed

2 files changed

+21
-3
lines changed

encode.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -278,7 +278,7 @@ func safeError(err error) (s string, ok bool) {
278278
if v := reflect.ValueOf(err); v.Kind() == reflect.Ptr && v.IsNil() {
279279
s, ok = "null", false
280280
} else {
281-
panic(panicVal)
281+
s, ok = fmt.Sprintf("PANIC:%v", panicVal), false
282282
}
283283
}
284284
}()
@@ -292,7 +292,7 @@ func safeString(str fmt.Stringer) (s string, ok bool) {
292292
if v := reflect.ValueOf(str); v.Kind() == reflect.Ptr && v.IsNil() {
293293
s, ok = "null", false
294294
} else {
295-
panic(panicVal)
295+
s, ok = fmt.Sprintf("PANIC:%v", panicVal), true
296296
}
297297
}
298298
}()
@@ -306,7 +306,7 @@ func safeMarshal(tm encoding.TextMarshaler) (b []byte, err error) {
306306
if v := reflect.ValueOf(tm); v.Kind() == reflect.Ptr && v.IsNil() {
307307
b, err = nil, nil
308308
} else {
309-
panic(panicVal)
309+
b, err = nil, fmt.Errorf("panic when marshalling: %s", panicVal)
310310
}
311311
}
312312
}()

encode_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,10 @@ func TestMarshalKeyvals(t *testing.T) {
125125
{in: kv(decimalStringer{5, 9}, "v"), want: []byte("5.9=v")},
126126
{in: kv((*decimalStringer)(nil), "v"), err: logfmt.ErrNilKey},
127127
{in: kv(marshalerStringer{5, 9}, "v"), want: []byte("5.9=v")},
128+
{in: kv("k", panicingStringer{0}), want: []byte("k=ok")},
129+
{in: kv("k", panicingStringer{1}), want: []byte("k=PANIC:panic1")},
130+
// Need extra mechanism to test panic-while-printing-panicVal
131+
//{in: kv("k", panicingStringer{2}), want: []byte("?")},
128132
}
129133

130134
for _, d := range data {
@@ -196,6 +200,20 @@ func (errorMarshaler) MarshalText() ([]byte, error) {
196200
return nil, errMarshal
197201
}
198202

203+
type panicingStringer struct {
204+
a int
205+
}
206+
207+
func (p panicingStringer) String() string {
208+
switch p.a {
209+
case 1:
210+
panic("panic1")
211+
case 2:
212+
panic(panicingStringer{a: 2})
213+
}
214+
return "ok"
215+
}
216+
199217
func BenchmarkEncodeKeyval(b *testing.B) {
200218
b.ReportAllocs()
201219
enc := logfmt.NewEncoder(ioutil.Discard)

0 commit comments

Comments
 (0)