How to prevent unhandled panic from crashing my application process

196 Views Asked by At

I want a mechanism by which any unhandled panic (from Go code) does not bring down my application process. At the moment any downstream panic(s) raised by my golang code will freeze/crash my application. How do I gracefully handle all panic(s) and still continue to serve my client applications?

1

There are 1 best solutions below

1
Abhishek Mali On
//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)
 }
}

Above following code will simply handle all panic's if recovery used in main function inside defer.