Skip to content

Instantly share code, notes, and snippets.

@komuw
Last active December 16, 2020 16:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save komuw/55a60df9322fb1488e5d9bd48a3dd47a to your computer and use it in GitHub Desktop.
Save komuw/55a60df9322fb1488e5d9bd48a3dd47a to your computer and use it in GitHub Desktop.
global panic handler in Go
package main
import "fmt"
// Usage:
//
// func main() {
// defer panicHandler()
// }
//
// Do note that this would not catch all panics.
// eg; `panic(nil)` will not be caught
//
func panicHandler() {
// keep an eye on the accepeted proposal: issues/37023
// https://github.com/golang/go/issues/37023
//
// Also keep an eye on proposal: issues/42888
// https://github.com/golang/go/issues/42888
r := recover()
if r != nil {
fmt.Println(`
\n
panicHandler recovered.
This is where you call your logging service.
And or your metric service to take error counts.
\n\n
`)
panic(r)
}
}
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/docker/docker/client"
"github.com/komuw/meli"
)
func main() {
defer panicHandler()
fmt.Println("Hello, main func")
docker()
}
func docker() {
fmt.Println("docker func called")
dc := &meli.DockerContainer{
ComposeService: meli.ComposeService{Image: "busybox"},
LogMedium: os.Stdout,
FollowLogs: true}
dc = nil // will cause panic
ctx := context.Background()
cli, err := client.NewEnvClient()
if err != nil {
log.Fatal(err, " :unable to intialize docker client")
}
defer cli.Close()
meli.LoadAuth() // load dockerhub info
err = meli.PullDockerImage(ctx, cli, dc)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment