包装try/catch
This commit is contained in:
95
try/default.go
Normal file
95
try/default.go
Normal file
@ -0,0 +1,95 @@
|
||||
// Package try ...
|
||||
//
|
||||
// Description : try ...
|
||||
//
|
||||
// Author : go_developer@163.com<白茶清欢>
|
||||
//
|
||||
// Date : 2023-07-20 12:13
|
||||
package try
|
||||
|
||||
// DefaultCatchHandler catch handler默认实现
|
||||
//
|
||||
// Author : go_developer@163.com<白茶清欢>
|
||||
//
|
||||
// Date : 12:14 2023/7/20
|
||||
type DefaultCatchHandler struct {
|
||||
hasDeal bool // 异常是否已被处理
|
||||
errCode string
|
||||
data map[string]interface{}
|
||||
}
|
||||
|
||||
// hasDealError 判断异常是否已经被处理
|
||||
//
|
||||
// Author : go_developer@163.com<白茶清欢>
|
||||
//
|
||||
// Date : 12:46 2023/7/20
|
||||
func (d *DefaultCatchHandler) hasDealError() bool {
|
||||
if d.hasDeal {
|
||||
return true
|
||||
}
|
||||
if d.errCode == "" {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Catch 处理指定errorCode
|
||||
//
|
||||
// Author : go_developer@163.com<白茶清欢>
|
||||
//
|
||||
// Date : 17:19 2023/7/20
|
||||
func (d *DefaultCatchHandler) Catch(errCode string, handler func(errCode string, data map[string]interface{})) ICatchHandler {
|
||||
if d.hasDealError() {
|
||||
return d
|
||||
}
|
||||
if errCode != d.errCode {
|
||||
return d
|
||||
}
|
||||
d.hasDeal = true
|
||||
defer func() {
|
||||
if r := recover(); nil != r {
|
||||
d.hasDeal = false
|
||||
d.data[errCode+"_handler_error"] = r.(error).Error()
|
||||
}
|
||||
}()
|
||||
handler(d.errCode, d.data)
|
||||
return d
|
||||
}
|
||||
|
||||
// CatchAll 捕捉任意一场
|
||||
//
|
||||
// Author : go_developer@163.com<白茶清欢>
|
||||
//
|
||||
// Date : 17:47 2023/7/20
|
||||
func (d *DefaultCatchHandler) CatchAll(handler func(errCode string, data map[string]interface{})) IFinalHandler {
|
||||
if d.hasDealError() {
|
||||
return d
|
||||
}
|
||||
defer func() {
|
||||
if r := recover(); nil != r {
|
||||
d.data[d.errCode+"_handler_error"] = r.(error).Error()
|
||||
}
|
||||
}()
|
||||
d.hasDeal = true
|
||||
handler(d.errCode, d.data)
|
||||
return d
|
||||
}
|
||||
|
||||
// Finally 最终逻辑
|
||||
//
|
||||
// Author : go_developer@163.com<白茶清欢>
|
||||
//
|
||||
// Date : 17:48 2023/7/20
|
||||
func (d *DefaultCatchHandler) Finally(data map[string]interface{}, handlers ...func(data map[string]interface{})) {
|
||||
if data == nil {
|
||||
data = map[string]interface{}{}
|
||||
}
|
||||
defer func() {
|
||||
if r := recover(); nil != r {
|
||||
|
||||
}
|
||||
}()
|
||||
for _, itemHandler := range handlers {
|
||||
itemHandler(data)
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user