getting panic() argument in defer function in GO lang -
i have function calling function b sometime call panic based on invalid data. in function defer function, know message function b passed panic() can report error in json on network client.
e.g.
func a( abc data) result string{ defer func(){ // panic args , return result. } xx = b( abc[0] ); yy = b( abc[1] ); ... }
the reason function b use panic avoid large amount of
err := b(abc) if err != nil { ... }
in function , make code easier read , maintain.
for example:
package main import ( "errors" "fmt" ) func a(s string) (result string, err error) { defer func() { if e := recover(); e != nil { switch x := e.(type) { case error: err = x default: err = fmt.errorf("%v", x) } } }() b(s) return "returned", nil } func b(s string) { switch s { case "ok": return case "fail": panic(errors.new("failed")) case "fail miserably": panic(42) default: a, b := 1, 0 if a/b != 0 { panic("ouch") } } } func main() { s, err := a("ok") fmt.printf("%q, %t(%#v)\n", s, err, err) s, err = a("fail") fmt.printf("%q, %t(%#v)\n", s, err, err) s, err = a("fail miserably") fmt.printf("%q, %t(%#v)\n", s, err, err) s, err = a("") fmt.printf("%q, %t(%#v)\n", s, err, err) }
output:
"returned", <nil>(<nil>) "", *errors.errorstring(&errors.errorstring{s:"failed"}) "", *errors.errorstring(&errors.errorstring{s:"42"}) "", runtime.errorstring("integer divide zero")
Comments
Post a Comment