add error template

master
Evan Chen 2021-11-12 07:58:54 +08:00
parent 0f342edffa
commit 0f740a700a
2 changed files with 30 additions and 0 deletions

27
error.go Normal file
View File

@ -0,0 +1,27 @@
package ksrv
import (
"encoding/json"
"fmt"
)
type Error struct {
Code int `json:"code"`
ID string `json:"id"`
Message string `json:"msg"`
Tmpl string `json:"-"`
}
func (e Error) New(v ...interface{}) Error {
e.Message = fmt.Sprintf(e.Tmpl, v...)
return e
}
func (e Error) Error() string {
return e.Message
}
func (e Error) Json() []byte {
data, _ := json.Marshal(e)
return data
}

3
net.go
View File

@ -41,6 +41,9 @@ func Abort(w http.ResponseWriter, errs ...interface{}) (int, error) {
msg := []byte{}
for _, err := range errs {
switch v := err.(type) {
case Error:
code = v.Code
msg = v.Json()
case int:
if v >= 100 || v < 600 {
code = v