mirror of
https://gitee.com/johng/gf.git
synced 2024-11-30 03:07:45 +08:00
增加g.Throw抛异常方法,g.TryCatch异常捕获方法封装
This commit is contained in:
parent
1d751345f7
commit
7fe089fc41
10
g/g_func.go
10
g/g_func.go
@ -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)
|
||||
}
|
@ -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()
|
||||
}
|
||||
|
||||
|
23
g/util/gutil/gutil_test.go
Normal file
23
g/util/gutil/gutil_test.go
Normal 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{}) {
|
||||
|
||||
})
|
||||
}
|
||||
}
|
@ -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()
|
||||
}
|
16
geg/util/gutil/try_catch.go
Normal file
16
geg/util/gutil/try_catch.go
Normal 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)
|
||||
})
|
||||
}
|
Loading…
Reference in New Issue
Block a user