-
Notifications
You must be signed in to change notification settings - Fork 224
Description
Since TOML is generally more user-facing, I think having the ability to generate custom error messages can be extremely helpful. Unfortunately, the only way I'm aware to do this right now is through implementing a custom TextMarshaler - and that can reach its limits very quickly, e.g. when the error occurs at a step that already requires the full document to be unmarshaled. I would really appreciate it if this library had some sort of way to trace back where a specific value came from, ideally with the ability to display a nicely formatted error message.
I implemented a crude version of this myself: xypwn@997b507, but it's definitely not ideal. The way it works is that there's a FieldPosition
type, which you can put after a struct field to record the original field's position into it. You can then use a Decoder method to acquire a function that will generate custom errors with a FieldPosition
's info.
Example:
var v struct {
Foo string
FooPos toml.FieldPosition
}
dec := toml.NewDecoder(strings.NewReader("Foo = 'baz'"))
makeErr := dec.ErrorMaker()
err := dec.Decode(&v)
if err != nil {
panic(err)
}
if v.Foo != "bar" {
fmt.Println(makeErr(v.FooPos, "Foo must equal 'bar'").(*toml.DecodeError).String())
}
// Output:
// 1| Foo = 'baz'
// | ~~~ foo must equal 'bar'
I'm not very familiar with this library and its codebase, so maybe someone else has a better idea of how this could be done in a more simple/reliable/performant way.