Skip to content

Commit d698e2f

Browse files
d2r2nicksnyder
authored andcommitted
Provide nice output of plural form not found error (#147)
1 parent cc0ca3b commit d698e2f

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

v2/internal/message_template.go

+16
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package internal
22

33
import (
44
"bytes"
5+
"fmt"
56

67
"text/template"
78

@@ -38,9 +39,24 @@ func setPluralTemplate(pluralTemplates map[plural.Form]*Template, pluralForm plu
3839
}
3940
}
4041

42+
type pluralFormNotFoundError struct {
43+
pluralForm plural.Form
44+
messageID string
45+
}
46+
47+
func (e pluralFormNotFoundError) Error() string {
48+
return fmt.Sprintf("message %q has no plural form %q", e.messageID, e.pluralForm)
49+
}
50+
4151
// Execute executes the template for the plural form and template data.
4252
func (mt *MessageTemplate) Execute(pluralForm plural.Form, data interface{}, funcs template.FuncMap) (string, error) {
4353
t := mt.PluralTemplates[pluralForm]
54+
if t == nil {
55+
return "", pluralFormNotFoundError{
56+
pluralForm: pluralForm,
57+
messageID: mt.Message.ID,
58+
}
59+
}
4460
if err := t.parse(mt.LeftDelim, mt.RightDelim, funcs); err != nil {
4561
return "", err
4662
}

v2/internal/message_template_test.go

+13
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package internal
22

33
import (
4+
"reflect"
45
"testing"
56

67
"github.com/nicksnyder/go-i18n/v2/internal/plural"
@@ -18,3 +19,15 @@ func TestNilMessageTemplate(t *testing.T) {
1819
panic(mt)
1920
}
2021
}
22+
23+
func TestMessageTemplatePluralFormMissing(t *testing.T) {
24+
mt := NewMessageTemplate(&Message{ID: "HelloWorld", Other: "Hello World"})
25+
s, err := mt.Execute(plural.Few, nil, nil)
26+
if s != "" {
27+
t.Errorf("expected %q; got %q", "", s)
28+
}
29+
expectedErr := pluralFormNotFoundError{pluralForm: plural.Few, messageID: "HelloWorld"}
30+
if !reflect.DeepEqual(err, expectedErr) {
31+
t.Errorf("expected error %#v; got %#v", expectedErr, err)
32+
}
33+
}

0 commit comments

Comments
 (0)