Go exception handle

ReZero lol

原文链接:https://blog.golang.org/error-handling-and-go

1
2
3
4
5
6
7
func Open(name string) (file *File, err error)

f, err := os.Open("filename.ext")
if err != nil {
log.Fatal(err)
}
// do something with the open *File f
  1. 函数的返回值附带一个 error 作为异常返回,当出现异常时其不为 nil

  2. error 是接口类型,只包含了一个字符串做描述,因此可以自己做实现。

    tips: Go 不需要显示的声明自己实现了什么接口,只要实现了接口的方法就代表实现了该接口,如下

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    type Shaper interface {
    Area() float32
    }

    type Square struct {
    side float32
    }

    func (sq *Square) Area() float32 {
    return sq.side * sq.side
    }

    func main() {
    sq1 := new(Square)
    sq1.side = 5

    var areaIntf Shaper
    areaIntf = sq1
    // shorter,without separate declaration:
    // areaIntf := Shaper(sq1)
    // or even:
    // areaIntf := sq1
    fmt.Printf("The square has area: %f\n", areaIntf.Area())
    }

  3. 异常扩展实现时断言的优雅处理

    • golang的语言中提供了断言的功能。golang中的所有程序都实现了interface{}的接口,这意味着,所有的类型如string,int,int64甚至是自定义的struct类型都就此拥有了interface{}的接口,这种做法和java中的Object类型比较类似。那么在一个数据通过func funcName(interface{})的方式传进来的时候,也就意味着这个参数被自动的转为interface{}的类型。
    • 果断言失败,那么ok的值将会是false,但是如果断言成功ok的值将会是true,同时value将会得到所期待的正确的值
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    type SyntaxError struct {
    msg string // description of error
    Offset int64 // error occurred after reading Offset bytes
    }

    func (e *SyntaxError) Error() string { return e.msg }

    if err := dec.Decode(&val); err != nil {
    if serr, ok := err.(*json.SyntaxError); ok {
    line, col := findLine(f, serr.Offset)
    return fmt.Errorf("%s:%d:%d: %v", f.Name(), line, col, err)
    }
    return err
    }
  4. 把 error handle 包裹为函数扔出去,使之成为其他函数的入参

  • Post title:Go exception handle
  • Post author:ReZero
  • Create time:2020-09-18 10:35:00
  • Post link:https://rezeros.github.io/2020/09/18/go-exception-handle/
  • Copyright Notice:All articles in this blog are licensed under BY-NC-SA unless stating additionally.
 Comments
Contents