Go的错误机制
- 没有异常机制
- error类型实现了error接口
type error interface {
Error() string
}
- 可以通过 errors.New来快速创建错误实例
errors.New("n must be in the range [0,10]")
示例代码
package err_test
import (
"fmt"
"github.com/pkg/errors"
"testing"
)
var LessThanTwoError = errors.New("n should be not less than 2")
var LargerhanHundredError = errors.New("n should be not less than 2")
func GetFibonaccin(n int) ([]int, error) {
if n < 2 {
return nil, LessThanTwoError
}
if n > 100 {
return nil, LargerhanHundredError
}
fibList := []int{1, 1}
for i := 2; i < n; i++ {
fibList = append(fibList, fibList[i-2]+fibList[i-1])
}
return fibList, nil
}
func TestGetFibonaccin(t *testing.T) {
if v, err := GetFibonaccin(1); err != nil {
if err == LessThanTwoError {
fmt.Println("It is less")
}
if err == LargerhanHundredError {
}
t.Log(err)
} else {
t.Log(v)
}
}
输出
=== RUN TestGetFibonaccin
It is less
--- PASS: TestGetFibonaccin (0.00s)
error_test.go:35: n should be not less than 2
PASS
Process finished with exit code 0
最佳实践
func GetFibonacci1(str string) {
var (
i int
err error
list []int
)
if i, err = strconv.Atoi(str); err == nil {
if list, err = GetFibonacci(i); err == nil {
fmt.Println(list)
} else {
fmt.Println("Error", err)
}
} else {
fmt.Println("Error", err)
}
}
func GetFibonacci2(str string) {
var (
i int
err error
list []int
)
if i, err = strconv.Atoi(str); err != nil {
fmt.Println("Error", err)
return
}
if list, err = GetFibonacci(i); err != nil {
fmt.Println("Error", err)
return
}
fmt.Println(list)
}