Skip to content

Commit 8daca65

Browse files
authored
fix(i18n): wrap parse error cause (#1319)
## What? - Wrap the JSON parser source error with `%w` instead of rendering it with `%v`. - Add regression coverage that preserves both `ErrParseFailed` and the original `json.SyntaxError` in the error chain. Closes #1050 ## Why? The i18n parser already wraps `ErrParseFailed`, but the underlying JSON parse error was converted to text. That made `errors.As` unable to recover the original cause from callers that need to inspect it.
1 parent cfbb604 commit 8daca65

2 files changed

Lines changed: 24 additions & 1 deletion

File tree

i18n/parser.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ type TranslationFile struct {
1515
func ParseJSON(data []byte) (MessageMap, error) {
1616
var file TranslationFile
1717
if err := json.Unmarshal(data, &file); err != nil {
18-
return nil, fmt.Errorf("%w: %v", ErrParseFailed, err)
18+
return nil, fmt.Errorf("%w: %w", ErrParseFailed, err)
1919
}
2020

2121
messages := make(MessageMap)

i18n/parser_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package i18n
2+
3+
import (
4+
"encoding/json"
5+
"errors"
6+
"testing"
7+
)
8+
9+
func TestParseJSONWrapsSyntaxError(t *testing.T) {
10+
_, err := ParseJSON([]byte(`{"language":"en","messages":`))
11+
if err == nil {
12+
t.Fatal("ParseJSON() error = nil, want parse error")
13+
}
14+
15+
if !errors.Is(err, ErrParseFailed) {
16+
t.Fatalf("ParseJSON() error = %v, want ErrParseFailed in chain", err)
17+
}
18+
19+
var syntaxErr *json.SyntaxError
20+
if !errors.As(err, &syntaxErr) {
21+
t.Fatalf("ParseJSON() error = %v, want json.SyntaxError in chain", err)
22+
}
23+
}

0 commit comments

Comments
 (0)