利用golang实现封装trycatch异常处理实例代码
前言
社区不少人在谈论 golang 为毛不用trycatch模式,而采用苛刻的recovery、panic、defer组合…. 从网上整了一个trycatch包,感觉不错,拿出来分享下…下面话不多说,来一起看看详细的介绍。
示例代码
package main import ( "reflect" ) type TryCatch struct { errChan chan interface{} catches map[reflect.Type]func(err error) defaultCatch func(err error) } func (t TryCatch) Try(block func()) TryCatch { t.errChan = make(chan interface{}) t.catches = map[reflect.Type]func(err error){} t.defaultCatch = func(err error) {} go func() { defer func() { t.errChan <- recover() }() block() }() return t } func (t TryCatch) CatchAll(block func(err error)) TryCatch { t.defaultCatch = block return t } func (t TryCatch) Catch(e error, block func(err error)) TryCatch { errorType := reflect.TypeOf(e) t.catches[errorType] = block return t } func (t TryCatch) Finally(block func()) TryCatch { err := <-t.errChan if err != nil { catch := t.catches[reflect.TypeOf(err)] if catch != nil { catch(err.(error)) } else { t.defaultCatch(err.(error)) } } block() return t } type MyError struct { error } func main() { TryCatch{}.Try(func() { println("do something buggy") panic(MyError{}) }).Catch(MyError{}, func(err error) { println("catch MyError") }).CatchAll(func(err error) { println("catch error") }).Finally(func() { println("finally do something") }) println("done") }
总结
相关推荐
zzjmay 2020-02-20
Cloudeep 2020-01-10
nuligannima 2013-06-26
jackalwb 2019-12-24
jackalwb 2019-12-15
hlfsunshine 2013-09-02
84334052 2019-11-19
xiaobaichen 2019-11-05
jiangtie 2019-11-02
Elmo 2019-10-27
IOSPanPan 2015-04-15
ice00 2019-08-04
yexiekai 2012-02-26
sufwei 2014-02-23
chermonlove 2019-08-02
atb 2013-06-26
caifengguo 2018-06-14
tonygsw 2014-11-30