Go语言 如何防止未处理的恐慌崩溃我的应用程序进程

8zzbczxx  于 2023-06-27  发布在  Go
关注(0)|答案(1)|浏览(57)

我想要一种机制,通过这种机制,任何未处理的panic(来自Go代码)都不会使我的应用程序进程崩溃。目前,我的golang代码引发的任何下游恐慌都会冻结/崩溃我的应用程序。我如何优雅地处理所有的死机,并且仍然继续为我的客户端应用程序提供服务?

yyhrrdl8

yyhrrdl81#

//You could use defer-recovery to handle all possible panic's 
func handelPanic(){
 if recoverPanic := recovery();recoverPanic != nil{
  fmt.Println("Panic is being recovered...")
   //Call function which you want to restart after panic is being recovered
 }
}    

func main() {
 defer handlePanic()
 //some code that needs to check err
 if err != nil{
     panic(err)
 }
}

上面下面的代码将简单地处理所有的恐慌,如果恢复使用在主函数内推迟。

相关问题