增加g.Throw抛异常方法,g.TryCatch异常捕获方法封装

This commit is contained in:
john 2018-11-06 13:53:06 +08:00
parent 1d751345f7
commit 7fe089fc41
5 changed files with 72 additions and 6 deletions

View File

@ -37,3 +37,13 @@ func Wait() {
func Dump(i...interface{}) {
gutil.Dump(i...)
}
// 抛出一个异常
func Throw(err interface{}) {
gutil.Throw(err)
}
// try...catch...
func TryCatch(try func(), catch func(err interface{})) {
gutil.TryCatch(try, catch)
}

View File

@ -65,3 +65,18 @@ func PrintBacktrace() {
glog.Header(false).Print(buffer.String())
}
// 抛出一个异常
func Throw(err interface{}) {
panic(err)
}
// try...catch...
func TryCatch(try func(), catch func(err interface{})) {
defer func() {
if err := recover(); err != nil {
catch(err)
}
}()
try()
}

View File

@ -0,0 +1,23 @@
// Copyright 2018 gf Author(https://gitee.com/johng/gf). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://gitee.com/johng/gf.
// go test *.go -bench=".*" -benchmem
package gutil
import (
"testing"
)
func Benchmark_TryCatch(b *testing.B) {
for i := 0; i < b.N; i++ {
TryCatch(func() {
}, func(err interface{}) {
})
}
}

View File

@ -1,14 +1,16 @@
package main
import (
"gitee.com/johng/gf/g"
"gitee.com/johng/gf/g/net/ghttp"
"fmt"
"gitee.com/johng/gf/g/util/gutil"
)
func main() {
g.Server().BindHandler("/", func(r *ghttp.Request) {
r.Response.Write(r.GetInt("amount"))
gutil.TryCatch(func() {
fmt.Println(1)
panic("error")
fmt.Println(2)
}, func(err interface{}) {
fmt.Println(err)
})
g.Server().SetPort(8199)
g.Server().Run()
}

View File

@ -0,0 +1,16 @@
package main
import (
"fmt"
"gitee.com/johng/gf/g/util/gutil"
)
func main() {
gutil.TryCatch(func() {
fmt.Println(1)
gutil.Throw("error")
fmt.Println(2)
}, func(err interface{}) {
fmt.Println(err)
})
}