Go错误实例

在Go语言编程中,它习惯于通过一个显式的,单独的返回值来传达错误。这与Java和Ruby等语言中使用的异常,以及有时在C语言中使用的重载的单个结果/错误值形成对比。Go语言编程的方法使得很容易看到哪些函数返回错误,并使用用于任何其他语言的相同语言构造来处理它们,非错误任务。

按照惯例,错误是最后一个返回值,并有类型:error,它是一个内置接口。通过对它们实现Error()方法,可以使用自定义类型作为错误。上面的例子使用自定义类型来显式地表示一个参数错误。

errors.New使用给定的错误消息构造基本错误值。错误位置中的nil值表示没有错误。

在这种情况下,使用&argError语法构建一个新的结构,为两个字段argprob提供值。

下面的两个循环测试每个错误返回函数。注意,使用if语句内联错误检查是Go代码中的常见作法。

如果要以编程方式使用自定义错误中的数据,则需要通过类型断言将错误作为自定义错误类型的实例。

所有的示例代码,都放在 F:\worksp\golang 目录下。安装Go编程环境请参考:/tutorial/detail-5562.html

errors.go的完整代码如下所示 -

package main

import "errors"
import "fmt"

// By convention, errors are the last return value and
// have type `error`, a built-in interface.
func f1(arg int) (int, error) {
    if arg == 42 {

        // `errors.New` constructs a basic `error` value
        // with the given error message.
        return -1, errors.New("can't work with 42")

    }

    // A nil value in the error position indicates that
    // there was no error.
    return arg + 3, nil
}

// It's possible to use custom types as `error`s by
// implementing the `Error()` method on them. Here's a
// variant on the example above that uses a custom type
// to explicitly represent an argument error.
type argError struct {
    arg  int
    prob string
}

func (e *argError) Error() string {
    return fmt.Sprintf("%d - %s", e.arg, e.prob)
}

func f2(arg int) (int, error) {
    if arg == 42 {

        // In this case we use `&argError` syntax to build
        // a new struct, supplying values for the two
        // fields `arg` and `prob`.
        return -1, &argError{arg, "can't work with it"}
    }
    return arg + 3, nil
}

func main() {

    // The two loops below test out each of our
    // error-returning functions. Note that the use of an
    // inline error check on the `if` line is a common
    // idiom in Go code.
    for _, i := range []int{7, 42} {
        if r, e := f1(i); e != nil {
            fmt.Println("f1 failed:", e)
        } else {
            fmt.Println("f1 worked:", r)
        }
    }
    for _, i := range []int{7, 42} {
        if r, e := f2(i); e != nil {
            fmt.Println("f2 failed:", e)
        } else {
            fmt.Println("f2 worked:", r)
        }
    }

    // If you want to programmatically use the data in
    // a custom error, you'll need to get the error  as an
    // instance of the custom error type via type
    // assertion.
    _, e := f2(42)
    if ae, ok := e.(*argError); ok {
        fmt.Println(ae.arg)
        fmt.Println(ae.prob)
    }
}

执行上面代码,将得到以下输出结果 -

F:\worksp\golang>go run errors.go
f1 worked: 10
f1 failed: can't work with 42
f2 worked: 10
f2 failed: 42 - can't work with it

can't work with it

上一篇:Go接口实例

下一篇:Go程序实例

关注微信小程序
程序员编程王-随时随地学编程

扫描二维码
程序员编程王

扫一扫关注最新编程教程