2 回答

TA貢獻1752條經(jīng)驗 獲得超4個贊
我認為您要問的更多是關(guān)于何時打印錯誤,而不是何時處理或不處理錯誤。就我而言,如果我認為它們將來對我有用,我喜歡打印所有可以打印的日志。
在您的情況下,消息可能logs.Error("Error while parsing ")過于冗長,因為您沒有在那里顯示任何詳細信息。
您可以考慮的其他方法是將您的自定義錯誤返回到頂層函數(shù)而不是更深層次的函數(shù),并且只在那里顯示日志消息。在示例的情況下應(yīng)該是這樣的:
func main() {
bma, err := Parse("path")
if err != nil {
log.Println(err)
return
}
}
func Parse(source string) (bma.Bma, error) {
file, err := ioutil.ReadFile(source + "bma.yaml")
m := bma.Bma{}
if err != nil {
return m, fmt.Errorf("Not able to read the bma file: %s", err.Error())
}
err = yaml.Unmarshal([]byte(file), &m)
if err != nil {
return m, fmt.Errorf("Not able to unmarshal the bma file: %s", err.Error())
}
return m, err
}

TA貢獻1818條經(jīng)驗 獲得超8個贊
package main
import (
"fmt"
"log"
"os"
)
func main() {
fileName := "main.go"
err := parse(fileName)
if err != nil {
log.Println(err)
}
log.Println(parse2(fileName))
log.Println(parse3(fileName))
//Incase of library one need to create new errors and export them
//see error.go file of some stdlib packages for some example
}
func parse(s string) error {
_, err := os.Open(s + "t") // fails
if err != nil {
// no need to add any custom err information,
// as err contains required details (action, fileName, error)
return err
}
return nil
}
func parse2(s string) error {
// Incase you must handle errors
_, err := os.Open(s + "t") // fails
if err != nil {
err = (err.(*os.PathError)).Err //only, if you must handle it
if err == os.ErrPermission {
//send notification to developer, about user
} else if err == os.ErrNotExist {
//user is so irresponsible, block him
} else if os.IsNotExist(err) {
fmt.Println("found the cause")
}
return err
}
return nil
}
func parse3(s string) error {
err := badError(s)
if err != nil {
// wrap error with required context information,
// if err doesn't return proper error
// or if you have more useful information
return fmt.Errorf("%s ,%s", s, err)
}
return nil
}
func badError(s string) error {
return fmt.Errorf("badError,I'm not saying why it failed, and what's the argument which caused me to fail, and making error without actually any content")
}
- 2 回答
- 0 關(guān)注
- 126 瀏覽
添加回答
舉報