-
Notifications
You must be signed in to change notification settings - Fork 18k
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
proposal: cmd/vet: diagnose marshal of field of type error #45108
Comments
The hard part here is false positives. It is technically fine to json.Marshal a field of type error when it is nil or when it contains a JSON-able error. If you only trigger when you know it's a non-JSON-able error, that would be a possibility. But that might have too many false negatives. |
This proposal has been added to the active column of the proposals project |
Based on the discussion above, this proposal seems like a likely decline. |
No change in consensus, so declined. |
This proposal is to add a new vet checker that warns when an exported
error
field of a struct is marshaled. Currently what will happen is that as error is an interface this will use the marshaling of the underlying type.error
values created byerrors.New()
andfmt.Errorf()
are currently implemented by structs with unexported string fields. The result is that the marshaled value is "{}".This behavior is well defined, but many users expect to see the "err.Error()" value. These would consider their code buggy. So this plausibly satisfies vet's correctness criteria.
Similar issues: #26946, #41241, #26889, #23549.
Example:
https://play.golang.org/p/XHoSKtGwAUN
Output:
The current focus is on
json.Marshal()
, but could be extended to similar standard library functions.To avoid spurious reports the proposed conditions to warn would be when:
json.Marshal(e)
expression,T
fore
, andT
reaches an exported error field (follow pointers, struct sub-fields, map fields, etc.) without traversing an interface or a type withMarshalJSON()
defined on it.These reports can potentially be considered false positives when all of the underlying types of the error values stored in the field have an MarshalJSON function defined or have a well defined serialization:
type MyErr string; func (MyErr) Error() string {...}
.This would not report flows through
interface{}
variables for functions wrappingjson.Marshall()
. Example of this pattern but not necessarily for error values here.The text was updated successfully, but these errors were encountered: