以try-catch的方式写go代码

guoapeng · · 1399 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

一直觉得golang 处理 异常的方式过于繁琐,有时优雅的链式写法,由于返回multiple-values, 不得不中断, 有了try-catch模块后,在try-catch模块中写代码就不必 因为每个链条上都要处理异常而中断了,可以在 catch函数里统一处理, 这是实现try-catch的初衷之一,例子稍后补上。下午突发奇想,借着一股冲劲把它写完了,欢迎大家拍砖或提出宝贵意见。 废话少说,直接上代码。 #Try description: A Go language implementation of try catch. Prerequisite: install golang 1.13 or later ## Installation Use `go get` to install SDK ```shell $ go get -u github.com/guoapeng/try ``` examples ```go package try_test import ( "fmt" . "github.com/guoapeng/try" ) func ExampleRuntimeError() { Try{ func(a, b, c int) (int,error) { return a/b, nil }}.Catch(func (ex error){ fmt.Println("error happens", ex) }).Go(4, 0, 3) // Output: // error happens runtime error: integer divide by zero } func ExampleCheckError() { Try{ func(a, b, c int) (int,error) { if a % b != 0 { return 0, fmt.Errorf("%d is not aliquot by %d", a, b) } return a/b, nil }}.Catch(func (ex error){ fmt.Println("error happens", ex) }).Go(5, 2, 3) // Output: // error happens 5 is not aliquot by 2 } func ExampleUpdateLocalVariable() { local := 100 Try{ func(a, b, c int) { local = a*b*c }}.Catch(func (ex error){ fmt.Println("error happens", ex) }).Go(5, 5, 5) fmt.Println(local) // Output: // 125 } func ExampleCheckHandlePanic() { Try{ func(a, b int) (int,error) { panic("mandatory service down") return a/b, nil }}.Catch(func (ex error){ fmt.Println("error happens", ex) }).Go(5, 2) // Output: // error happens mandatory service down } func ExampleHandleMultipleDatType() { Try{ func(a string , b, c int) { fmt.Println(a, b/c) }}.Catch(func (ex error){ fmt.Println("error happens", ex) }).Go("b/c =", 8, 2) // Output: // b/c = 4 } func ExampleHowToReturnValue() { r := divide(8, 4) fmt.Println("8/4 =", r) //Output: // 8/4 = 2 } func ExampleHowToThrowException() { Try{func() { r := divideThrowsRuntimeExption(8, 0) fmt.Println("8/4 =", r) }} .Catch(func(ex error) { fmt.Println("error handled at point B:", ex) }).Go() //Output: // error handled at point B: it can't be handle at point A - runtime error: integer divide by zero } func divideThrowsRuntimeExption(x, y int) (z int) { Try{func(a, b int) { z = a / b return }}.Catch(func(ex error) { if err, ok := ex.(error); ok { panic(fmt.Errorf("it can't be handle at point A - %s", err)) } fmt.Println("error happens", ex) }).Go(x, y) return } func divide(x, y int) (z int) { Try{func(a, b int) { z = a / b return }}.Catch(func(ex error) { fmt.Println("error happens", ex) }).Go(x, y) return } ```

有疑问加站长微信联系(非本文作者))

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1399 次点击  ∙  1 赞  
加入收藏 微博
3 回复  |  直到 2019-10-11 18:40:47
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传