From 91a6a2a30f95da8ae3fb6329a71c49ed13aa12ad Mon Sep 17 00:00:00 2001 From: Joe Tsai Date: Tue, 5 Dec 2017 22:53:48 -0800 Subject: encoding/json: make error capture logic in recover more type safe Rather than only ignoring runtime.Error panics, which are a very narrow set of possible panic values, switch it such that the json package only captures panic values that have been properly wrapped in a jsonError struct. This ensures that only intentional panics originating from the json package are captured. Fixes #23012 Change-Id: I5e85200259edd2abb1b0512ce6cc288849151a6d Reviewed-on: https://go-review.googlesource.com/94019 Run-TryBot: Joe Tsai TryBot-Result: Gobot Gobot Reviewed-by: Brad Fitzpatrick --- src/encoding/json/encode.go | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) (limited to 'src/encoding/json/encode.go') diff --git a/src/encoding/json/encode.go b/src/encoding/json/encode.go index 1e45e445d9..68512d0225 100644 --- a/src/encoding/json/encode.go +++ b/src/encoding/json/encode.go @@ -17,7 +17,6 @@ import ( "fmt" "math" "reflect" - "runtime" "sort" "strconv" "strings" @@ -286,21 +285,20 @@ func newEncodeState() *encodeState { func (e *encodeState) marshal(v interface{}, opts encOpts) (err error) { defer func() { if r := recover(); r != nil { - if _, ok := r.(runtime.Error); ok { + if je, ok := r.(jsonError); ok { + err = je.error + } else { panic(r) } - if s, ok := r.(string); ok { - panic(s) - } - err = r.(error) } }() e.reflectValue(reflect.ValueOf(v), opts) return nil } +// error aborts the encoding by panicking with err wrapped in jsonError. func (e *encodeState) error(err error) { - panic(err) + panic(jsonError{err}) } func isEmptyValue(v reflect.Value) bool { -- cgit v1.3