diff --git a/g/g_func.go b/g/g_func.go index 78459c0e0..28751ca14 100644 --- a/g/g_func.go +++ b/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) +} \ No newline at end of file diff --git a/g/util/gutil/gutil.go b/g/util/gutil/gutil.go index 553190f04..efdf3fc90 100644 --- a/g/util/gutil/gutil.go +++ b/g/util/gutil/gutil.go @@ -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() +} + diff --git a/g/util/gutil/gutil_test.go b/g/util/gutil/gutil_test.go new file mode 100644 index 000000000..0e92c0252 --- /dev/null +++ b/g/util/gutil/gutil_test.go @@ -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{}) { + + }) + } +} diff --git a/geg/other/test.go b/geg/other/test.go index a0577e76a..6319394aa 100644 --- a/geg/other/test.go +++ b/geg/other/test.go @@ -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() } \ No newline at end of file diff --git a/geg/util/gutil/try_catch.go b/geg/util/gutil/try_catch.go new file mode 100644 index 000000000..10084db4e --- /dev/null +++ b/geg/util/gutil/try_catch.go @@ -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) + }) +} \ No newline at end of file