2 回答

TA貢獻(xiàn)1719條經(jīng)驗(yàn) 獲得超6個(gè)贊
典型的Go代碼(使用該os程序包)沒有分析返回的錯(cuò)誤對(duì)象。它只是將錯(cuò)誤消息打印給用戶(然后,用戶根據(jù)打印的消息知道出了什么問題),或者將錯(cuò)誤原樣返回給調(diào)用者。
如果要阻止程序打開不存在的文件,或者要檢查文件是否可讀/可寫,我建議在打開文件之前使用os.Stat函數(shù)。
您可以分析返回錯(cuò)誤的Go類型,但這似乎很不方便:
package main
import "fmt"
import "os"
func main() {
_, err := os.Open("non-existent")
if err != nil {
fmt.Printf("err has type %T\n", err)
if err2, ok := err.(*os.PathError); ok {
fmt.Printf("err2 has type %T\n", err2.Error)
if errno, ok := err2.Error.(os.Errno); ok {
fmt.Fprintf(os.Stderr, "errno=%d\n", int64(errno))
}
}
fmt.Fprintf(os.Stderr, "%s\n", err)
os.Exit(1)
}
}
打?。?/p>
err has type *os.PathError
err2 has type os.Errno
errno=2
open non-existent: no such file or directory
- 2 回答
- 0 關(guān)注
- 363 瀏覽
添加回答
舉報(bào)