Contents

Why recover() Does Nothing for a panic in Go

Contents

We had an intermittent panic we couldn’t pin down, so the quick move was to wrap it in recover(), log the context, and keep the service running. Except the branch that was supposed to run never got there.

The rule for recover is: once a panic happens, the program jumps to the deferred function that contains recover(); recover() catches the panic and it stops propagating. The important part — execution does not resume at the point of the panic. It continues from wherever recover() sits.

So if the panic comes from go f() running in a different goroutine, and recover() is written outside that goroutine, the two are never in the same goroutine and recover can’t possibly fire.

Wrong — the deferred recover lives outside the goroutine that panics:

func test() {
    defer func() {
        if err := recover(); err != nil {
            fmt.Println("panic")
        }
    }()
    go f()
}

Right — the defer goes inside the goroutine:

func test() {
    go func() {
        defer func() {
            if err := recover(); err != nil {
                fmt.Println("panic")
            }
        }()
        f()
    }()
}