一、定义错误
import ( "errors" "testing" ) var LessThanTwoError = errors.New("n should bu in [0,100]") //菲波拉数列 变量赋值 func GetFibonacci(n int) ([]int, error) { //及早失败 if n < 0 { return nil, LessThanTwoError } fibList := []int{1, 1} for i := 2; i < n; i++ { fibList = append(fibList, fibList[i-1]+fibList[i-2]) } return fibList[:n], nil } func TestExchange(t *testing.T) { if v, err := GetFibonacci(-10); err != nil { t.Error(err) } else { t.Log(v) } }
=== RUN TestExchange error_test.go:25: n should bu in [0,100] --- FAIL: TestExchange (0.00s) FAIL
二、panic、recover()
panic:抛出错误;
recover():捕捉错误;
import ( "errors" "fmt" "testing" ) //panic用不不可以恢复的错误 //panic退出前会执行defer指定的内容 //os.Exit退出不会执行defer,没有栈调用信息 func TestPaincVxExit(t *testing.T) { defer func() { fmt.Println("Finally!") }() defer func() { if err := recover(); err != nil { fmt.Println("recover from", err) } }() fmt.Println("start") panic(errors.New("something wrong!")) //os.Exit(-1) }
=== RUN TestPaincVxExit start recover from something wrong! Finally! --- PASS: TestPaincVxExit (0.00s) PASS