1
0
mirror of https://github.com/go-kratos/kratos.git synced 2025-03-25 21:38:59 +02:00
包子 0834128e57
add protoc-gen-errors (#1017)
* add protoc-gen-errors

* fix protoc-gen-go-errors/go.mod

* default_code handling

* Modify code value range
2021-06-08 16:33:50 +08:00

46 lines
826 B
Go

package main
import (
"bytes"
"text/template"
)
var errorsTemplate = `
{{ range .Errors }}
func Is{{.Value}}(err error) bool {
e := errors.FromError(err)
if e.Reason == {{.Name}}_{{.Value}}.String() && e.Code == {{.HttpCode}} {
return true
}
return false
}
func Error{{.Value}}(format string, args ...interface{}) *errors.Error {
return errors.New({{.HttpCode}}, {{.Name}}_{{.Value}}.String(), fmt.Sprintf(format, args...))
}
{{- end }}
`
type errorInfo struct {
Name string
Value string
HttpCode int
}
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)
}
return string(buf.Bytes())
}