Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Setting custom errors in Decoder.SetErr #155

Closed
mike76-dev opened this issue Apr 17, 2024 · 1 comment
Closed

Setting custom errors in Decoder.SetErr #155

mike76-dev opened this issue Apr 17, 2024 · 1 comment

Comments

@mike76-dev
Copy link
Contributor

I'm struggling with this code:

// SetErr sets the Decoder's error if it has not already been set. SetErr should
// only be called from DecodeFrom methods.
func (d *Decoder) SetErr(err error) {
	if err != nil && d.err == nil {
		d.err = err
		// clear d.buf so that future reads always return zero
		d.buf = [len(d.buf)]byte{}
	}
}

I'm writing a compat code where I'm reading a struct that may or may not contain a field. If it doesn't contain that field, I need to set d.err to nil or a custom error that will indicate upstream that the compat code has executed. Currently this is not possible, because changing the d.err value is only possible when it's nil, but in my case it's EOF.

@github-project-automation github-project-automation bot moved this to Triage in Sia Apr 17, 2024
@ChrisSchinnerl
Copy link
Member

SetErr is not allowing overwriting errors on purpose, because doing so might hide the root error causing an issue.

When dealing with versioning the ideal solution is usually storing/sending the version first and then continue decoding accordingly.
If that is not possible, another approach is to first try and decode into the new type and if that fails try to decode into the old type. If the latter succeeds you know it was the old one. That's not as nice as the first approach but works usually.

@github-project-automation github-project-automation bot moved this from Triage to Done in Sia Apr 17, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: Done
Development

No branches or pull requests

2 participants