2016-03-14 456 views
12

從文檔上log.Fatalln()什麼時候應該在golang中使用panic vs log.fatalln()?

FUNC Fatalln(V ...接口{})Fatalln相當於給println() 隨後通過調用os.Exit(1)。

source code爲Fatalln:

310 // Fatalln is equivalent to Println() followed by a call to os.Exit(1). 
    311 func Fatalln(v ...interface{}) { 
    312  std.Output(2, fmt.Sprintln(v...)) 
    313  os.Exit(1) 
    314 } 

看來主要區別在於是否有錯誤,現在是可恢復的(因爲你可以恢復恐慌) - 還有什麼更顯著不同它們之間?

恐慌的接口definition是:

215 // The panic built-in function stops normal execution of the current 
    216 // goroutine. When a function F calls panic, normal execution of F stops 
    217 // immediately. Any functions whose execution was deferred by F are run in 
    218 // the usual way, and then F returns to its caller. To the caller G, the 
    219 // invocation of F then behaves like a call to panic, terminating G's 
    220 // execution and running any deferred functions. This continues until all 
    221 // functions in the executing goroutine have stopped, in reverse order. At 
    222 // that point, the program is terminated and the error condition is reported, 
    223 // including the value of the argument to panic. This termination sequence 
    224 // is called panicking and can be controlled by the built-in function 
    225 // recover. 
    226 func panic(v interface{}) 

看來恐慌不返回任何東西。

這是主要的區別嗎?否則,他們似乎在應用程序中執行相同的功能,假設恐慌未被恢復。

+1

考慮閱讀[官方博客](https://blog.golang.org/defer-panic-and-recover),其中恐慌和恢復很好地解釋 – pupizoid

回答

9
  • 日誌消息進入配置的日誌輸出,而恐慌只會寫入標準錯誤。

  • Panic將打印一個堆棧跟蹤,它可能與錯誤無關。

  • 當程序發生混亂時,將延遲執行,但是立即調用os.Exit,並且延遲功能無法運行。

一般情況下,只使用panic編程錯誤,其中的堆棧跟蹤到錯誤的情況下非常重要。如果消息不是針對程序員的,則只需將消息隱藏在多餘的數據中。

+0

因此,在測試的情況下,似乎恐慌會更好然後?因爲它們是針對程序員的。 – enderland

+1

@enderland:如果堆棧跟蹤是相關的(我知道我不希望在測試時發現無用的堆棧跟蹤信息,但是有關故障的簡單消息就足夠了),這隻會是恐慌。如果你只需要寫出一條錯誤信息,那麼只需寫下該信息即可。 (如果可能,也可以使用't.Fatal' /'t.Fatalf'與登錄測試) – JimB

相關問題