在Go語(yǔ)言編程中,它習(xí)慣于通過(guò)一個(gè)顯式的,單獨(dú)的返回值來(lái)傳達(dá)錯(cuò)誤。這與Java和Ruby等語(yǔ)言中使用的異常,以及有時(shí)在C語(yǔ)言中使用的重載的單個(gè)結(jié)果/錯(cuò)誤值形成對(duì)比。Go語(yǔ)言編程的方法使得很容易看到哪些函數(shù)返回錯(cuò)誤,并使用用于任何其他語(yǔ)言的相同語(yǔ)言構(gòu)造來(lái)處理它們,非錯(cuò)誤任務(wù)。
按照慣例,錯(cuò)誤是最后一個(gè)返回值,并有類型:error,它是一個(gè)內(nèi)置接口。通過(guò)對(duì)它們實(shí)現(xiàn)Error()方法,可以使用自定義類型作為錯(cuò)誤。上面的例子使用自定義類型來(lái)顯式地表示一個(gè)參數(shù)錯(cuò)誤。
errors.New使用給定的錯(cuò)誤消息構(gòu)造基本錯(cuò)誤值。錯(cuò)誤位置中的nil值表示沒(méi)有錯(cuò)誤。
在這種情況下,使用&argError語(yǔ)法構(gòu)建一個(gè)新的結(jié)構(gòu),為兩個(gè)字段arg和prob提供值。
下面的兩個(gè)循環(huán)測(cè)試每個(gè)錯(cuò)誤返回函數(shù)。注意,使用if語(yǔ)句內(nèi)聯(lián)錯(cuò)誤檢查是Go代碼中的常見(jiàn)作法。
如果要以編程方式使用自定義錯(cuò)誤中的數(shù)據(jù),則需要通過(guò)類型斷言將錯(cuò)誤作為自定義錯(cuò)誤類型的實(shí)例。
所有的示例代碼,都放在
F:\worksp\golang目錄下。安裝Go編程環(huán)境請(qǐng)參考:http://www.yiibai.com/go/go_environment.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)
}
}
執(zhí)行上面代碼,將得到以下輸出結(jié)果 -
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
42
can't work with it