Skip to content

Instantly share code, notes, and snippets.

@ictlyh
Created April 26, 2020 02:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ictlyh/838d7c4985fba38acd9ffa2c9fb80298 to your computer and use it in GitHub Desktop.
Save ictlyh/838d7c4985fba38acd9ffa2c9fb80298 to your computer and use it in GitHub Desktop.
package errors
import (
"fmt"
"reflect"
"strconv"
)
type CodedError struct {
code int64 // 错误码
err string // 错误信息(内部使用)
msg string // 错误信息(用户提示)
}
func (codedErr *CodedError) Code() int64 {
return codedErr.code
}
func (codedErr *CodedError) Error() string {
return codedErr.err
}
func (codedErr *CodedError) Message() string {
return codedErr.msg
}
func (codedErr *CodedError) WithMessage(msg string) *CodedError {
codedErr.msg = msg
return codedErr
}
// 通用错误码
type CommonErr struct {
Ok *CodedError `code:"0" err:"ok" msg:"success"`
InvalidParam *CodedError `code:"1" err:"无效参数" msg:"无效参数,请修改后重试"`
}
// 业务错误码
var ArticlePublishErr = &struct {
CommonErr *CommonErr
InternalError *CodedError `code:"2" err:"内部错误" msg:"内部错误,请稍后重试"`
}{}
func initErrorContainerByTag(obj interface{}) {
objT := reflect.TypeOf(obj).Elem()
objV := reflect.ValueOf(obj).Elem()
for i := 0; i < objT.NumField(); i++ {
fieldT := objT.Field(i)
fieldV := objV.Field(i)
tag := fieldT.Tag
fieldV.Set(reflect.New(fieldT.Type.Elem()))
if fieldT.Name == "CommonErr" {
initErrorContainerByTag(fieldV.Interface())
} else if v, ok := fieldV.Interface().(*CodedError); ok {
code, _ := strconv.ParseInt(tag.Get("code"), 10, 0)
v.code = code
v.err, v.msg = tag.Get("err"), tag.Get("msg")
if v.err == "" {
v.err = v.msg
}
}
}
}
func init() {
initErrorContainerByTag(ArticlePublishErr)
}
func TestError() {
invalidParam := ArticlePublishErr.CommonErr.InvalidParam
internalError := ArticlePublishErr.InternalError.WithMessage("修改一下提示信息")
fmt.Printf("code=%d, err=%s, msg=%s\n", invalidParam.code, invalidParam.err, invalidParam.msg)
fmt.Printf("code=%d, err=%s, msg=%s\n", internalError.code, internalError.err, internalError.msg)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment