Panic is a built-in function that stops the ordinary flow of control and begins panicking. — blog.golang.org
Panic.
I was scary to hear that. It’s sounds like terrible crash. But If you using golang, as we all know, there is no exception in Go. Just Panic.
Example of panic runtime slice bounds out of range :
package mainimport (
"fmt"
)func main() {
h := "Hello"
substring := h[0:6] // Here is the panic
fmt.Println(substring)
}
Output :
panic: runtime error: slice bounds out of range [:6] with length 5
goroutine 1 [running]:
main.main()
/tmp/sandbox094013890/prog.go:9 +0x1d
So what go propose?
Recover is a built-in function that regains control of a panicking goroutine. Recover is only useful inside deferred functions. — blog.golang.org
Recover.
It was gracefully help to handle the panic. To use this method, we have to defer it. Because it will executed after return functions.
defer will executed after end of function, return, and panic also.
Example to use recover to handle the panic :
package mainimport (
"fmt"
)func main() {
defer Recover()
h := "Hello"
substring := h[0:6] // Here is the panic
fmt.Println(substring)
}func Recover() {
if r := recover(); r != nil {
fmt.Println("Recovered!")
}
}
Output :
Recovered!
Well done ! It’s ready for production!
Also we need to add this recover in every goroutines (sounds redundant). But maybe you want to different recover for some goroutines, for example: HttpRecover, ConsumerRecover, WorkerRecover, etc.
Additionally, I found some libraries to help as panic wrapper
or handler
or catcher
our panic runtime that we can follow :
Conclusion
We should handle panic, we never know what happen in your code. Maybe sometimes it crash because the input, parameters, validation, logic, or whatever it is. We should recover it.
Thanks god there is recover and easy use. With recover, there is no panic, just handle it with you want. You can send it as notification, or log, or just let it go.
Do not panic. Recover it.
Thank You !