2021-06-08 16:33:50 +08:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"text/template"
|
|
|
|
)
|
|
|
|
|
|
|
|
var errorsTemplate = `
|
|
|
|
{{ range .Errors }}
|
|
|
|
|
2022-05-20 15:35:20 +08:00
|
|
|
{{ if .HasComment }}{{ .Comment }}{{ end -}}
|
2021-06-08 16:53:08 +08:00
|
|
|
func Is{{.CamelValue}}(err error) bool {
|
2021-12-20 11:10:01 +08:00
|
|
|
if err == nil {
|
|
|
|
return false
|
|
|
|
}
|
2021-06-08 16:33:50 +08:00
|
|
|
e := errors.FromError(err)
|
2022-05-20 15:35:20 +08:00
|
|
|
return e.Reason == {{ .Name }}_{{ .Value }}.String() && e.Code == {{ .HTTPCode }}
|
2021-06-08 16:33:50 +08:00
|
|
|
}
|
|
|
|
|
2022-05-20 15:35:20 +08:00
|
|
|
{{ if .HasComment }}{{ .Comment }}{{ end -}}
|
|
|
|
func Error{{ .CamelValue }}(format string, args ...interface{}) *errors.Error {
|
|
|
|
return errors.New({{ .HTTPCode }}, {{ .Name }}_{{ .Value }}.String(), fmt.Sprintf(format, args...))
|
2021-06-08 16:33:50 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
{{- end }}
|
|
|
|
`
|
|
|
|
|
|
|
|
type errorInfo struct {
|
2021-06-08 16:53:08 +08:00
|
|
|
Name string
|
|
|
|
Value string
|
2021-09-07 10:46:46 +08:00
|
|
|
HTTPCode int
|
2021-06-08 16:53:08 +08:00
|
|
|
CamelValue string
|
2022-05-05 10:13:09 +08:00
|
|
|
Comment string
|
|
|
|
HasComment bool
|
2021-06-08 16:33:50 +08:00
|
|
|
}
|
2021-09-07 10:46:46 +08:00
|
|
|
|
2021-06-08 16:33:50 +08:00
|
|
|
type errorWrapper struct {
|
|
|
|
Errors []*errorInfo
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e *errorWrapper) execute() string {
|
|
|
|
buf := new(bytes.Buffer)
|
|
|
|
tmpl, err := template.New("errors").Parse(errorsTemplate)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
if err := tmpl.Execute(buf, e); err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
2021-09-07 10:46:46 +08:00
|
|
|
return buf.String()
|
2021-06-08 16:33:50 +08:00
|
|
|
}
|