title: global recover handler for golang http panic
body: <p>I want to create global err handler to send it by email.</p>
  <pre><code>package main
  
  import (
      &quot;github.com/gorilla/mux&quot;
      &quot;log&quot;
      &quot;net/http&quot;
  )
  
  func main() {
      rtr := mux.NewRouter()
      rtr.HandleFunc(&quot;/&quot;, withPanic).Methods(&quot;GET&quot;)
  
      http.Handle(&quot;/&quot;, rtr)
      log.Println(&quot;Listening...&quot;)
  
      http.ListenAndServe(&quot;:3001&quot;, http.DefaultServeMux)
  }
  
  func withPanic(w http.ResponseWriter, r *http.Request) {
      panic(&quot;somewhere here will be panic, but I don't know where exactly&quot;)
  }
  </code></pre>
  <p>How to make it global. It would be easy if I know where error will occur</p>
  <pre><code>if err != nil {
  sendMeMail(err)
  }
  </code></pre>
  <p>But what to do in cases when I don't know exactly where an error will occur? So I should add a global <code>recover</code>ish handler. But how to do it exactly I don't know.</p>
  <h1>Update</h1>
  <p>I added <code>defer recover</code> to beginning of <code>main</code> but it never executes on requesting <code>http://localhost:3001</code>. So panic is not emailed.</p>
  <pre><code>package main
  
  import (
      &quot;errors&quot;
      &quot;fmt&quot;
      &quot;github.com/gorilla/mux&quot;
      &quot;log&quot;
      &quot;net/http&quot;
  )
  
  func main() {
      defer func() {
          if r := recover(); r != nil {
              fmt.Println(&quot;Recovered in f&quot;, r)
              // find out exactly what the error was and set err
              var err error
              switch x := r.(type) {
              case string:
                  err = errors.New(x)
              case error:
                  err = x
              default:
                  err = errors.New(&quot;Unknown panic&quot;)
              }
              if err != nil {
                  // sendMeMail(err)
                  fmt.Println(&quot;sendMeMail&quot;)
              }
          }
      }()
      rtr := mux.NewRouter()
      rtr.HandleFunc(&quot;/&quot;, withPanic).Methods(&quot;GET&quot;)
  
      http.Handle(&quot;/&quot;, rtr)
      log.Println(&quot;Listening...&quot;)
  
      http.ListenAndServe(&quot;:3001&quot;, http.DefaultServeMux)
  }
  
  func withPanic(w http.ResponseWriter, r *http.Request) {
      panic(&quot;somewhere here will be panic, but I don't know where exactly&quot;)
  }
  </code></pre>