不要 panic
发布者:admin 发表于:444天前 阅读数:591 评论:0

在生产环境中运行的代码必须避免出现 panic。panic 是 cascading failures 级联失败的主要根源 。如果发生错误,该函数必须返回错误,并允许调用方决定如何处理它。

Bad Good

func run(args []string) { if len(args) == 0 { panic("an argument is required") } // ... }

func main() { run(os.Args[1:]) } |

func run(args []string) error { if len(args) == 0 { return errors.New("an argument is required") } // ... return nil }

func main() { if err := run(os.Args[1:]); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } |

panic/recover 不是错误处理策略。仅当发生不可恢复的事情(例如:nil 引用)时,程序才必须 panic。程序初始化是一个例外:程序启动时应使程序中止的不良情况可能会引起 panic。

var _statusTemplate = template.Must(template.New("name").Parse("_statusHTML"))

即使在测试代码中,也优先使用t.Fatal或者t.FailNow而不是 panic 来确保失败被标记。

Bad Good

// func TestFoo(t *testing.T)

f, err := ioutil.TempFile("", "test") if err != nil { panic("failed to set up test") } |

// func TestFoo(t *testing.T)

f, err := ioutil.TempFile("", "test") if err != nil { t.Fatal("failed to set up test") } |