🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
### 处理错误 ``` package main import ( "fmt" "io/ioutil" ) func main() { f, err := ioutil.ReadFile("test.txt") if err != nil { fmt.Println(err) } else { fmt.Println(f) } } 结果: open test.txt: The system cannot find the file specified. ``` ### 自定义错误 ``` type error interface{ Error() string } ``` ``` err := errors.New("this is an error") ``` ``` package main import ( "errors" "fmt" ) func main() { err := errors.New("这是错误程序") var err2 error fmt.Println(err.Error()) fmt.Println(err2) } 结果: 这是错误程序 <nil> ``` ``` package main import ( "fmt" "runtime" ) func main() { if _, _, line, ok := runtime.Caller(0); ok == true { err := fmt.Errorf("错误出现在%d行", line) fmt.Println(err.Error()) } } 结果: 错误出现在9行 ```