参考:
Golang中的error类型: https://studygolang.com/articles/4389
文档:https://studygolang.com/pkgdoc
类的方法实现了接口的全部方法,就说此类实现了接口,并可以把此类赋值给这个接口
// The error built-in interface type is the conventional interface for
// representing an error condition, with the nil value representing no error.
type error interface { error类型本身就是一个预定义好的接口,里面定义了一个method
Error() string
}
---------------
type Error struct {
Code model.ErrorType `json:"code"`
Msg string `json:"msg"`
}
func (e Error) Error() string { 实现上面的Error接口方法
bytes, _ := json.Marshal(e)
return string(bytes)
}
---------------
func (s *articleStore) ArticleInfoGet(sn int64) (*model.ArticleInfo, error) { error
//从缓存获取
if articleMeta, err := ArticleRedis.ArticleInfoGet(sn); err == nil {
return articleMeta, nil
}
//从Mysql获取
articleInfo, err := ArticleMysql.GetArticleInfo(sn, true)
if err != nil || articleInfo == nil {
return nil, commonErrors.ErrNotFound() 返回Error类型~~~对比上面的额error
}
if articleInfo.DeletedAt == nil {
//文章写入缓存
if err := ArticleRedis.ArticleInfoSave(articleInfo); err != nil {
//日志
logrus.Errorf("save article meta to redis err, article %+v, err %v", articleInfo, err)
}
}
return articleInfo, nil
}
---------------
// 请求资源未找到
func ErrNotFound() Error {
return Error{ Error类型
Code: NotFound,
Msg: "The resource you were trying to find could not be found.",
}
}
---------------
func Err(err error) Response {
if eErr, ok := err.(errors.Error); ok { 使用类型断言 过滤err的类别
return Response{
Code: eErr.Code,
Msg: eErr.Msg,
}
}
logrus.Error(err)
return Response{
Code: errors.Unknown,
Msg: "未知错误",
}
}