增加try-cache
This commit is contained in:
90
try/catch.go
Normal file
90
try/catch.go
Normal file
@ -0,0 +1,90 @@
|
||||
// Package try...
|
||||
//
|
||||
// Description : catch 的实现
|
||||
//
|
||||
// Author : go_developer@163.com<白茶清欢>
|
||||
//
|
||||
// Date : 2021-07-24 10:10 下午
|
||||
package try
|
||||
|
||||
import "reflect"
|
||||
|
||||
// CatchHandler catch的处理
|
||||
//
|
||||
// Author : go_developer@163.com<白茶清欢>
|
||||
//
|
||||
// Date : 9:55 下午 2021/7/24
|
||||
type CatchHandler struct {
|
||||
err error // 异常
|
||||
hasDeal bool // 是否已处理
|
||||
}
|
||||
|
||||
// NeedDeal 是否需要处理 : 存在异常切异常没有处理过
|
||||
//
|
||||
// Author : go_developer@163.com<白茶清欢>
|
||||
//
|
||||
// Date : 9:57 下午 2021/7/24
|
||||
func (ch *CatchHandler) NeedDeal() bool {
|
||||
return nil != ch.err && !ch.hasDeal
|
||||
}
|
||||
|
||||
// HasError 判断是否有异常
|
||||
//
|
||||
// Author : go_developer@163.com<白茶清欢>
|
||||
//
|
||||
// Date : 10:00 下午 2021/7/24
|
||||
func (ch *CatchHandler) HasError() bool {
|
||||
return ch.err != nil
|
||||
}
|
||||
|
||||
// ErrorHasDeal 异常已经处理
|
||||
//
|
||||
// Author : go_developer@163.com<白茶清欢>
|
||||
//
|
||||
// Date : 10:01 下午 2021/7/24
|
||||
func (ch *CatchHandler) ErrorHasDeal() bool {
|
||||
return ch.hasDeal
|
||||
}
|
||||
|
||||
// Catch ...
|
||||
//
|
||||
// Author : go_developer@163.com<白茶清欢>
|
||||
//
|
||||
// Date : 10:29 下午 2021/7/24
|
||||
func (ch *CatchHandler) Catch(err error, handler func(err2 error)) ICatchHandler {
|
||||
if !ch.NeedDeal() {
|
||||
return ch
|
||||
}
|
||||
//如果传入的error类型和发生异常的类型一致,则执行异常处理器,并将hasCatch修改为true代表已捕捉异常
|
||||
if reflect.TypeOf(err) == reflect.TypeOf(ch.err) {
|
||||
handler(ch.err)
|
||||
ch.hasDeal = true
|
||||
}
|
||||
return ch
|
||||
}
|
||||
|
||||
// CatchAll ...
|
||||
//
|
||||
// Author : go_developer@163.com<白茶清欢>
|
||||
//
|
||||
// Date : 10:29 下午 2021/7/24
|
||||
func (ch *CatchHandler) CatchAll(handler func(err error)) FinalHandler {
|
||||
if !ch.NeedDeal() {
|
||||
return ch
|
||||
}
|
||||
handler(ch.err)
|
||||
ch.hasDeal = true
|
||||
return ch
|
||||
}
|
||||
|
||||
func (ch *CatchHandler) Finally(handlers ...func()) {
|
||||
// 遍历处理器,并在Finally函数执行完毕之后执行
|
||||
for _, handler := range handlers {
|
||||
defer handler()
|
||||
}
|
||||
err := ch.err
|
||||
//<7>如果异常不为空,且未捕捉异常,则抛出异常
|
||||
if err != nil && !ch.hasDeal {
|
||||
panic(err)
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user