feat: typed decode and encode errors with the key path
Assisted-by: GLM 5.3 Flash
This commit is contained in:
@@ -1160,3 +1160,73 @@ type Custom struct {
|
||||
}
|
||||
|
||||
func (c Custom) MarshalTOML() (any, error) { return c.tag, nil }
|
||||
|
||||
// encodeErrBad is a Marshaler whose MarshalTOML always fails.
|
||||
type encodeErrBad struct {
|
||||
msg string
|
||||
}
|
||||
|
||||
func (encodeErrBad) MarshalTOML() (any, error) { return nil, errors.New("bad timestamp") }
|
||||
|
||||
func TestEncodeErrorCarriesPath(t *testing.T) {
|
||||
type Inner struct {
|
||||
Port encodeErrBad `toml:"port"`
|
||||
}
|
||||
type Cfg struct {
|
||||
Server Inner `toml:"server"`
|
||||
}
|
||||
_, err := Marshal(Cfg{Server: Inner{Port: encodeErrBad{}}})
|
||||
if err == nil {
|
||||
t.Fatal("expected a marshal error")
|
||||
}
|
||||
ee, ok := errors.AsType[*EncodeError](err)
|
||||
if !ok {
|
||||
t.Fatalf("expected an *EncodeError, got %T: %v", err, err)
|
||||
}
|
||||
if ee.Path != "server.port" {
|
||||
t.Fatalf("Path = %q, want %q", ee.Path, "server.port")
|
||||
}
|
||||
if ee.Err == nil || ee.Err.Error() != "bad timestamp" {
|
||||
t.Fatalf("Err = %v", ee.Err)
|
||||
}
|
||||
if err.Error() != "interpres: server.port: bad timestamp" {
|
||||
t.Fatalf("message = %q", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func TestEncodeErrorTopLevelPathHasNoLeadingDot(t *testing.T) {
|
||||
type Cfg struct {
|
||||
Port encodeErrBad `toml:"port"`
|
||||
}
|
||||
_, err := Marshal(Cfg{})
|
||||
ee, ok := errors.AsType[*EncodeError](err)
|
||||
if !ok {
|
||||
t.Fatalf("expected an *EncodeError, got %T: %v", err, err)
|
||||
}
|
||||
if ee.Path != "port" {
|
||||
t.Fatalf("Path = %q, want %q", ee.Path, "port")
|
||||
}
|
||||
if err.Error() != "interpres: port: bad timestamp" {
|
||||
t.Fatalf("message = %q", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func TestEncodeErrorHeterogeneousArrayPath(t *testing.T) {
|
||||
type Item struct {
|
||||
N int `toml:"n"`
|
||||
}
|
||||
cfg := map[string]any{
|
||||
"items": []any{Item{}, 3},
|
||||
}
|
||||
_, err := Marshal(cfg)
|
||||
if err == nil {
|
||||
t.Fatal("expected a heterogeneous array error")
|
||||
}
|
||||
ee, ok := errors.AsType[*EncodeError](err)
|
||||
if !ok {
|
||||
t.Fatalf("expected an *EncodeError, got %T: %v", err, err)
|
||||
}
|
||||
if ee.Path != "items[0]" {
|
||||
t.Fatalf("Path = %q, want %q", ee.Path, "items[0]")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user