前言
社区不少人在谈论 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") }
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。
如对本文有疑问, 点击进行留言回复!!
VSCode1.4 搭建Golang的开发调试环境(遇到很多问题)
网友评论