服务级别错误:
// Author: Mjy
// Create Date: 2018-11-23
package errno
import "fmt"
// 错误码定义
type Errno struct {
Code int `json:"code"`
Message string `json:"message"` // 对外展示的 message
}
func (err Errno) Error() string {
return err.Message
}
func New(errno *Errno, err error) *Err {
return &Err{Code: errno.Code, Message: errno.Message, Err: err}
}
// Err represents an error
// return 的错误
type Err struct {
Code int
Message string // 对外展示的 message
Err error // 内部 log 使用的 error
}
func (err *Err) Error() string {
return fmt.Sprintf("Err - code: %d, message: %v, errors: %v", err.Code, err.Message, err.Err)
}
func (err *Err) Add(message string) error {
err.Message += " " + message
return err
}
func (err *Err) Addf(format string, args ...interface{}) error {
err.Message += " " + fmt.Sprintf(format, args...)
return err
}
func IsErrUserNotFound(err error) bool {
code, _ := DecodeErr(err)
return code == ErrUserNotFound.Code
}
func DecodeErr(err error) (int, string) {
if err == nil {
return OK.Code, OK.Message
}
switch typed := err.(type) {
case *Err:
return typed.Code, typed.Message
case *Errno:
return typed.Code, typed.Message
default:
}
return InternalServerError.Code, err.Error()
}
// Author: Mjy
// Create Date: 2018-11-23
package errno
var (
// Common errors
OK = &Errno{Code: 0, Message: "OK"}
InternalServerError = &Errno{Code: 10001, Message: "Internal server error"}
ErrBind = &Errno{Code: 10002, Message: "Error occurred while binding the request body to the struct"}
// user errors
ErrUserNotFound = &Errno{Code: 20102, Message: "The user was not found."}
)
func Create(c *gin.Context) {
var r struct {
Username string `json:"username"`
Password string `json:"password"`
}
var err error
if err := c.Bind(&r); err != nil {
c.JSON(http.StatusOK, gin.H{"error": errno.ErrBind})
return
}
utils.PrintJson(r)
log.Debugf("username is: [%s], password is [%s]", r.Username, r.Password)
if r.Username == "" {
err = errno.New(errno.ErrUserNotFound, fmt.Errorf("username can not found in db: xx.xx.xx.xx")).Add("This is add message.")
log.Errorf(err, "Get an error")
}
if errno.IsErrUserNotFound(err) {
log.Debug("err type is ErrUserNotFound")
}
if r.Password == "" {
err = fmt.Errorf("password is empty")
}
code, message := errno.DecodeErr(err)
c.JSON(http.StatusOK, gin.H{"code": code, "message": message})
}