标准库的errors包不能完全满足我们的业务需求,通常我们需要自己创建一个错误包
1. 自定义error类型
Go中自定义error是非常简单的,实现Error() string接口即可
package errcodetype Error struct {Code int `json:"code"`Msg string `json:"msg"`Details []string `json:"details"`}func (e *Error) Error() string {return fmt.Sprintf("错误码:%d 错误信息:%s \n", e.Code, e.Msg)}
2. 新增创建Error的方法
var codes = make(map[int]string)func NewError(code int, msg string) *Error {if _, ok := codes[code]; !ok {panic(fmt.Sprintf("错误码%d已存在,请更换一个", code))}codes[code] = msgreturn &Error{Code: code,Msg: msg,}}// 在原错误上创建一个带有更过细节信息的错误func (e *Error) WithDetails(details ...string) *Error {newError := *enewError.Details = make([]string, 0)for _, d := range details {newError.Details = append(newError.Details, d)}reutrn &newError}
3. 自定义常用错误
var (Success = NewError(0, "成功")ServerError = NewError(10000000, "服务内部错误")InvalidParams = NewError(10000001, "入参错误")NotFound = NewError(10000002, "找不到")UnauthorizedAuthNotExist = NewError(10000003, "鉴权失败,找不到对应的用户")UnauthorizedTokenError = NewError(10000004, "鉴权失败,token错误")UnauthorizedTokenTimeout = NewError(10000005, "鉴权失败,token超时")UnauthorizedTokenGenerate = NewError(10000006, "鉴权失败,token生成失败")TooManyRequests = NewError(10000007, "请求过多")IdempotenceTokenError = NewError(10000008, "幂等性token错误"))
4. 新增错误码转响应码方法
func (e *Error) StatusCode() int {switch e.Code {case Success.Code:return http.StatusOKcase ServerError.Code:return http.StatusInternalServerErrorcase InvalidParams.Code:return http.StatusBadRequestcase NotFound.Code:return http.StatusNotFoundcase UnauthorizedAuthNotExist.Code:fallthroughcase UnauthorizedTokenError.Code:fallthroughcase UnauthorizedTokenTimeout.Code:fallthroughcase UnauthorizedTokenGenerate.Code:return http.StatusUnauthorizedcase TooManyRequests.Code:return http.StatusTooManyRequest}return http.StatusInternalServerError}
5. 总结
- 自定义错误类型直接实现error接口即可
- 自定义常用错误方便使用
- 自定义创建错误方便携带更过细节信息
