You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Right now the way these errors are being defined and used is quite error prone, specifically as it relates to how we are using the message and params. If a developer doesn't correctly match the number of formatting directives in the message, it will panic when Error is called.
We can do better :-)
First, we should have a New method as that is much safer than manually defining the structs.
Second we should make the params more dynamic.
New Method
The new method should be something like this.
// We should also add some type safety heretypeCodestringfuncNew(codeCode, msgstring) (Error, error) {
e:=Error{Code: code, Message: msg}
err=e.validate()
iferr!=nil {
returnnil, err
}
returne, nil
}
func (e*Error) validate() error {
deferfunc() {
ifr:=recover(); r!=nil {
returnfmt.Errorf("invalid Error: %v",r)
}
}()
_=e.Error()
returnnil
}
Dynamic Params
Instead of relying on a fixed formatted method, we could allow for dynamic params by expecting a key value pair.
func (e*Error) WithParams(params...interface{}) {
iflen(params)%2!=0 {
// Using panic for simplicity of example, but this is a discussion point as to how to handle the errorpanic("Error: Odd number of parameters, expected key-value pairs")
}
e.Params=append(e.Params, params...)
returne
}
func (e*Error) Error() string {
msg:=e.Messagefori:=0; i<len(e.Params); i+=2 {
key:=params[i]
value:=params[i+1]
msg=fmt.Sprintf("%s; %v: %v",msg, key, value)
}
ife.Err!=nil {
returnfmt.Sprintf("%s; error: %v", msg, e.Err)
}
returnmsg
}
The text was updated successfully, but these errors were encountered:
Saw your comment about creating an issue a bit late, I have applied those on the original PR.
Thanks for adding the New method, that is a good start.
I think there are still other parts of this issue that we should discuss.
Lower priority though.
Right now the way these errors are being defined and used is quite error prone, specifically as it relates to how we are using the message and params. If a developer doesn't correctly match the number of formatting directives in the message, it will panic when
Error
is called.We can do better :-)
First, we should have a
New
method as that is much safer than manually defining the structs.Second we should make the params more dynamic.
New Method
The new method should be something like this.
Dynamic Params
Instead of relying on a fixed formatted method, we could allow for dynamic params by expecting a key value pair.
The text was updated successfully, but these errors were encountered: