OnceFunc Rethrows The Same Panic

sync.OnceFunc replays the same panic value on every call after setup fails, unlike Once.Do where a panicking init is skipped as done.

GoResilience

Code

gosnippet
30 lines
package main

import (
	"fmt"
	"sync"
)

var onceSetup = sync.OnceFunc(func() {
	panic("config file missing")
})

func handle(name string) (result string) {
	defer func() {
		if r := recover(); r != nil {
			result = fmt.Sprintf("%s: setup panicked: %v", name, r)
		}
	}()
	onceSetup()
	return name + ": ready"
}

func main() {
	// OnceFunc rethrows the same panic value on every call
	fmt.Println(handle("first"))

	// the second call replays the same panic instead of counting as done
	fmt.Println(handle("second"))

	fmt.Println(handle("third"))
}

What the demo replays

onceSetup wraps a function that panics with config file missing. Each handle call runs onceSetup under a deferred recover, so the panic is captured per request and turned into a result string naming the caller.

Three calls print the same setup panicked text three times: sync.OnceFunc rethrows the stored panic value on every invocation after the failed init, unlike Once.Do, which treats a panicking function as done and skips later calls.

Practical notes

  • recover sees the original panic value string each time.
  • The named return result is what lets the deferred func replace the outcome.

Interactive Tools for This Topic

FAQ

How does OnceFunc differ from Once.Do on panic?
Once.Do marks a panicking init as complete and later calls return silently; OnceFunc remembers the panic and replays it to every caller, which is why all three printed lines carry the same setup panicked text.