What to do after a panic?

I searched a lot for this and i couldn’t find a clear answer, if i have a running system (say an HTTP server) what do i do if one of my functions panics ?, a lot of people seem to say that you should have some middleware or similar mechanism that catches the panic, logs the error and terminates the request with a 500 error response.

I primarily used Node js in the past, and the best practice there is to log the error and exit the process with an error code.

So what’s the “Go” way to deal with such a situation ?.

thanks for reading

If you exit the process your server will not continue to run.

I’m not an experienced Go programmer myself but what I’ve seen so far are

  1. Handle panics yourself:
func myFuncThatCanPanic(){
   defer func() {
       if r := recover(); r != nil {
           //Handle your panic as error here
   //Do some code that could panic
  1. Use a handler function. This is easy if you use GIN for example:
engine := gin.New()
// Recovery returns a middleware that recovers from any panics and writes a 500 if there was one.

Hope this helps

That seems reasonable to me. Do you have a reason to not do this?

Wouldn’t it be possible to leak resources (memory, file descriptors) if you didn’t have deferred calls that freed used resources (closed file descriptors, and connections).

Make sure the defer that cleans up resources occurs before the call to a function that may panic.

Example Go Playground - The Go Programming Language

Yes, if you do not use defer to handle cleaning up, then that cleanup won’t happen in the case of a panic, but you should be using defer to clean up those resources in the first place.


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.