var ( // ReallyCrash controls the behavior of HandleCrash and now defaults // true. It's still exposed so components can optionally set to false // to restore prior behavior. // 说ReallyCrash参数是暴露给组件的,开发者可以自行设置为false也可以按默认的true. ReallyCrash = true ) // PanicHandlers is a list of functions which will be invoked when a panic happens. // 拆开来看,PanicHandlers是一个列表,元素是函数的列表。函数传参类型是interface。默认的一个函数是logPanic var PanicHandlers = []func(interface{}){ logPanic, } // HandleCrash simply catches a crash and logs an error. Meant to be called via // defer. Additional context-specific handlers can be provided, and will be // called in case of panic. HandleCrash actually crashes, after calling the // handlers and logging the panic message. // // E.g., you can provide one or more additional handlers for something like shutting down go routines gracefully. // 通过参数可以看到HandleCrash是支持开发者自定义处理函数的。 func HandleCrash(additionalHandlers ...func(interface{})) { // recover是go内置的一个函数。位置在 D:\go1.16.7\src\builtin\builtin.go // 这里是主动执行recover函数,看返回结果是否nil,非nil表示确实出现了panic。 if r := recover(); r != nil { // 遍历列表PanicHandlers,逐个执行函数,这里会执行默认设置的函数logPanic, for _, fn := range PanicHandlers { fn(r) } // 执行用户自定义的处理函数 for _, fn := range additionalHandlers { fn(r) } // 注意一个坑点,这里是默认true。。需要你手动设置为false。不然程序panic后不会recover。。 if ReallyCrash { // Actually proceed to panic. panic(r) } } } func logPanic(r interface{}) { // 内容省略 }