Golang一种优雅的处理error的方式(泛型实现)
2024-01-25 本文已影响0人
Tenny1225
func E0(params ...interface{}) {
if params != nil && len(params) > 0 {
switch params[len(params)-1].(type) {
case error:
panic(params[len(params)-1])
}
}
}
func E1[T any](params ...interface{}) T {
var t T
if params != nil && len(params) > 0 {
switch params[len(params)-1].(type) {
case error:
panic(params[len(params)-1])
}
t = params[0].(T)
}
return t
}
func E2[T1, T2 any](params ...interface{}) (T1, T2) {
var t1 T1
var t2 T2
if params != nil && len(params) > 0 {
switch params[len(params)-1].(type) {
case error:
panic(params[len(params)-1])
}
t1 = params[0].(T1)
t2 = params[1].(T2)
}
return t1, t2
}
func E3[T1, T2, T3 any](params ...interface{}) (T1, T2, T3) {
var t1 T1
var t2 T2
var t3 T3
if params != nil && len(params) > 0 {
switch params[len(params)-1].(type) {
case error:
panic(params[len(params)-1])
}
t1 = params[0].(T1)
t2 = params[1].(T2)
t3 = params[2].(T3)
}
return t1, t2, t3
}
func E4[T1, T2, T3, T4 any](params ...interface{}) (T1, T2, T3, T4) {
var t1 T1
var t2 T2
var t3 T3
var t4 T4
if params != nil && len(params) > 0 {
switch params[len(params)-1].(type) {
case error:
panic(params[len(params)-1])
}
t1 = params[0].(T1)
t2 = params[1].(T2)
t3 = params[2].(T3)
t4 = params[3].(T4)
}
return t1, t2, t3, t4
}
func HandleError(err *error) {
if e := recover(); e != nil {
*err = fmt.Errorf("%e", e)
return
}
}
func plus(a, b int) (int, error) {
if a+b >= 0 {
return a + b, nil
}
return 0, errors.New("params error")
}
func test() (a int, e error) {
//e error必须要在返回值里面定义,不然会拿不到
defer HandleError(&e)
a += E1[int](plus(0, 1))
a += E1[int](plus(3, 1))
//出现error会中断执行
a += E1[int](plus(-5, 1))
return
}
func main() {
fmt.Println(test())
}