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

binding.Error 和 validator.Error 行为不一致 #32

Open
XIELongDragon opened this issue Aug 6, 2021 · 2 comments
Open

binding.Error 和 validator.Error 行为不一致 #32

XIELongDragon opened this issue Aug 6, 2021 · 2 comments

Comments

@XIELongDragon
Copy link
Contributor

当使用msg自定义错误信息时
validator的Error的行为是,如果有自定义错误信息就只返回自定义信息

// Error implements error interface.
func (e *Error) Error() string {
	if e.Msg != "" {
		return e.Msg
	}
	return "invalid parameter: " + e.FailPath
}

而binding的Error却会有其他附加信息

func (e *Error) Error() string {
	if e.Msg != "" {
		return e.ErrType + ": expr_path=" + e.FailField + ", cause=" + e.Msg
	}
	return e.ErrType + ": expr_path=" + e.FailField + ", cause=invalid"
}

建议,

  1. 两者的行为应该一致。
  2. 可以考虑在e.Msg支持占位符,由用户自己决定想要的错误信息格式。如
placeholders := map[string]string {"{{ ErrType }}":e.ErrType, "{{ FailField  }}":e..FailField }
msg := e.Msg

for k, v := range placeholders{
    msg = strings.Replace(msg, k, v)
}

return msg
@andeya
Copy link
Member

andeya commented Aug 6, 2021

两个包都提供了SetErrorFactory函数,支持自定义。其中binding的SetErrorFactory会自动设置其内部validator的error格式
https://github.com/bytedance/go-tagexpr/blob/master/binding/default.go#L35
https://github.com/bytedance/go-tagexpr/blob/master/validator/default.go#L23

@andeya
Copy link
Member

andeya commented Aug 6, 2021

你提的模板变量这个思路,作为默认实现也不错,我有空实现一下吧

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants