2011-12-21 44 views
1

我是Go的新手(到目前爲止花費了30分鐘!),並試圖做File I/O。如何在Go中調用os.Open(<filename>)時檢查錯誤?

file, ok := os.Open("../../sample.txt") 
    if ok != nil { 
    // error handling code here 
    os.Exit(1) 
    } 
    ... 

當呼叫失敗時,是不是應該返回一個錯誤號?這個調用返回os.Error,除'String()'之外沒有其他方法。

這是推薦方法來檢查Go中的錯誤?

回答

3

典型Go代碼(它使用os包)不分析所述返回的錯誤的對象。它只是向用戶打印錯誤消息(誰知道哪裏出錯了基於打印的消息)或返回錯誤原樣給調用者。

如果您想防止程序打開不存在的文件,或者想要檢查文件是否可讀/可寫,我會在打開文件之前建議使用os.Stat函數。

你可以分析轉到類型返回的錯誤的,但這似乎不方便:

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) 
    } 
} 

它打印:

err has type *os.PathError 
err2 has type os.Errno 
errno=2 
open non-existent: no such file or directory