diff --git a/hooks.go b/hooks.go index 808f562..a92ec53 100644 --- a/hooks.go +++ b/hooks.go @@ -138,7 +138,11 @@ func markLocalesLoaded() { // OnMissingKey registers a handler for missing translation keys. func OnMissingKey(h MissingKeyHandler) { - SetMissingKeyHandlers(h) + if h == nil { + ClearMissingKeyHandlers() + return + } + AddMissingKeyHandler(h) } // SetMissingKeyHandlers replaces the full missing-key handler chain. diff --git a/hooks_test.go b/hooks_test.go index f8fea46..66ea35e 100644 --- a/hooks_test.go +++ b/hooks_test.go @@ -543,6 +543,33 @@ func TestOnMissingKey_Good(t *testing.T) { assert.Equal(t, "hooks_test.go", filepath.Base(captured.CallerFile)) } +func TestOnMissingKey_Good_AppendsHandlers(t *testing.T) { + svc, err := New() + require.NoError(t, err) + prev := Default() + SetDefault(svc) + prevHandlers := missingKeyHandlers() + t.Cleanup(func() { + missingKeyHandler.Store(prevHandlers) + SetDefault(prev) + }) + + svc.SetMode(ModeCollect) + ClearMissingKeyHandlers() + t.Cleanup(func() { + ClearMissingKeyHandlers() + }) + + var first, second int + OnMissingKey(func(MissingKey) { first++ }) + OnMissingKey(func(MissingKey) { second++ }) + + _ = T("missing.on.handler.append") + + assert.Equal(t, 1, first) + assert.Equal(t, 1, second) +} + func TestAddMissingKeyHandler_Good(t *testing.T) { svc, err := New() require.NoError(t, err)