golang中panic的处理没有其他语言中try-catch语法那么简单。
大部分例子的panic处理都是在退出环节。那么如何在正常业务流程中处理panic,然后不影响全局呢?
// 业务处理1,定义myStrcture
isDone := make(chan int)
go func() {
defer func() {
if err := recover(); err != nil {
log.E(this.Ctx, "Skip panic", "tmpInfo=[%+v]", tmpInfo)
}
isDone <- 1
}()
myStrcture.Ip = tmpInfo.Ip
myStrcture.Country = tmpInfo.Address.Country.Name //可能panic
myStrcture.Province = tmpInfo.Address.Province.Name
myStrcture.City = tmpInfo.Address.City.Name
myStrcture.District = tmpInfo.Address.District.Name
}()
<-isDone
// 业务处理2
// 返回 myStrcture