Go:使用Error的几种姿势

Talk is cheap, I will show you the code.

总的来说,error 一共有3种用法:

1. 第一种夹带私货。使用struct结果包裹,提供更多的信息。

2. 还是基于struct , 加上了更多的逻辑的判断。

3. error变量的直接比较。在标准库中很常见。
package main

import "errors"
import "fmt"


//第一种姿势
type MyError struct {
    Op  string
    Err error
}

func (e *MyError) Error() string { return e.Op + " " + e.Err.Error() }

func test() error { return &MyError{"Op string", errors.New("this is my err")} }


//第二种姿势
type DNSError struct {
    Err error
}

func (e *DNSError) Error() string {
    return e.Err.Error()
}

func (e *DNSError) Timeout() bool {
    return true
}

func (e *DNSError) Temporary() bool {
    return false
}

//第三种姿势
var testErr = errors.New("this is my err")

func testErrFunc() error { return testErr }

func main() {

    a := test()
    if b, ok := a.(*MyError); ok {
        fmt.Println(b)
    }

    c := DNSError{errors.New("DNS ERRror")}
    if c.Temporary() {
        return
    } else if c.Timeout() {
        fmt.Println(c)
    }

    if testErr == testErrFunc() {
        fmt.Println("Err is equal")
    }
}
output:

Op string this is my err
{DNS ERRror}
Err is equal