package errors import "net/http" import "github.com/novalagung/gubrak" var ( unknownCoder ErrCode = ErrCode{1, http.StatusInternalServerError, "An internal server error occurred", ""} ) type ErrCode struct { // 业务错误码 C int // http码 HTTP int // 对外展示错误信息 Ext string // 引用 Ref string } func (coder ErrCode) Code() int { return coder.C } func (coder ErrCode) String() string { return coder.Ext } func (coder ErrCode) Reference() string { return coder.Ref } func (coder ErrCode) HTTPStatus() int { if coder.HTTP == 0 { return http.StatusInternalServerError } return coder.HTTP } func RegisterCode(code int, httpStatus int, message string, refs ...string) { found, _ := gubrak.Includes([]int{200, 400, 401, 403, 404, 500}, httpStatus) if !found { panic("http code not in `200, 400, 401, 403, 404, 500`") } var reference string if len(refs) > 0 { reference = refs[0] } coder := &ErrCode{ C: code, HTTP: httpStatus, Ext: message, Ref: reference, } MustRegister(coder) }