github.com/sandwich-go/boost@v1.3.29/xpanic/try.go (about) 1 package xpanic 2 3 // https://github.com/manucorporat/try/blob/master/try.go 4 5 const rethrow_panic = "_____rethrow" 6 7 type ( 8 E interface{} 9 exception struct { 10 finally func() 11 Error E 12 } 13 ) 14 15 func Throw() { 16 panic(rethrow_panic) 17 } 18 19 func Try(f func()) (e exception) { 20 e = exception{nil, nil} 21 // catch error in 22 defer func() { 23 e.Error = recover() 24 }() 25 f() 26 return 27 } 28 29 func (e exception) Catch(f func(err E)) { 30 if e.Error != nil { 31 defer func() { 32 // call finally 33 if e.finally != nil { 34 e.finally() 35 } 36 37 // rethrow exceptions 38 if err := recover(); err != nil { 39 if err == rethrow_panic { 40 err = e.Error 41 } 42 panic(err) 43 } 44 }() 45 f(e.Error) 46 } else if e.finally != nil { 47 e.finally() 48 } 49 } 50 51 func (e exception) Finally(f func()) (e2 exception) { 52 if e.finally != nil { 53 panic("finally was only set") 54 } 55 e2 = e 56 e2.finally = f 57 return 58 }