1 package emperror 2 3 import ( 4 "errors" 5 "fmt" 6 ) 7 8 // Recover accepts a recovered panic (if any) and converts it to an error (if necessary). 9 func Recover(r interface{}) (err error) { 10 if r != nil { 11 switch x := r.(type) { 12 case string: 13 err = errors.New(x) 14 case error: 15 err = x 16 default: 17 err = fmt.Errorf("unknown panic, received: %v", r) 18 } 19 20 if _, ok := StackTrace(err); !ok { 21 err = &wrappedError{ 22 err: err, 23 stack: callers()[2:], // TODO: improve callers? 24 } 25 } 26 } 27 28 return err 29 } 30