It is a sample of java-style try-catch-like implement in go. just so so.
type public struct {
error
any
}
type ctxTry struct {
public
}
type Exception struct {
public
}
type ctxCatch struct {
public
}
func (c *ctxCatch) Finally(fn func(e *Exception)) {
fn((*Exception)(c))
}
func (c *ctxTry) Catch(fn func(e *Exception) error) *ctxCatch {
return &ctxCatch{public{error: fn((*Exception)(c))}}
}
func (c *ctxTry) Finally(fn func(e *Exception)) {
fn((*Exception)(c))
}
type Context interface {
Finally(e *Exception)
}
func Try(fn func() error) (c *ctxTry) {
defer func() {
if err := recover(); err != nil {
c = new(ctxTry)
marshal, _ := json.Marshal(err)
c.public = public{error: errors.New(string(marshal))}
}
}()
err := fn()
return &ctxTry{public{error: err}}
}
func demo() {
Try(func() error {
return nil
}).Catch(func(e *Exception) error {
return nil
}).Finally(func(e *Exception) {
})
Try(func() error {
return nil
}).Finally(func(e *Exception) {
})
}