在 Go 中獲取字串中的錯誤訊息

錯誤值可以儲存在變數中,作為函式的引數提供,從函式返回等等,就像任何其他內建型別(如 int、float64、string 等)一樣。
本教程將在 Go 中檢索錯誤訊息作為字串。
使用 Go 中的檔案錯誤獲取字串中的錯誤訊息
在本例中,我們將嘗試開啟 /test_file.txt
。如果檔案成功開啟,Open
方法將返回檔案處理程式,錯誤將為 nil。
如果檔案無法開啟,將返回一個非零錯誤。
package main
import (
"fmt"
"os"
)
func main() {
f, err := os.Open("/test_file.txt")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(f.Name(), "Filed opened successfully")
}
輸出:
open /test_file.txt: no such file or directory
在 Go 中使用 Errorf()
獲取字串中的錯誤訊息
fmt.Errorf()
方法允許我們使用格式化工具在 Go 程式語言中構建有意義的錯誤訊息。
package main
import (
"fmt"
"time"
)
func main() {
err := fmt.Errorf("error occurred at: %v", time.Now())
fmt.Println("Error:", err)
}
輸出:
Error: error occurred at: 2022-03-04 23:00:00 +0000 UTC m=+0.000000001
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe