代码拉取完成,页面将自动刷新
判断 令牌过期
业务异常的使用方式:
err := Biz_Call()
if err == TokenExpired {
}
字符串比对, 可能造成误杀
access token expired %f minutes
hasPrefix("access token expired")
设计一套业务专用的业务异常, 通常设计为异常码(Error Code):
// err.ErrorCode == xxxx
if exception.IsTokenExpired(err) {
}
本书需要兼容Error的场景:
func XXX() error
go 里面的Error是个接口
// 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() string
}
fmt包里面提供的Error实现
type wrapError struct {
msg string
err error
}
func (e *wrapError) Error() string {
return e.msg
}
func (e *wrapError) Unwrap() error {
return e.err
}
type wrapErrors struct {
msg string
errs []error
}
func (e *wrapErrors) Error() string {
return e.msg
}
func (e *wrapErrors) Unwrap() []error {
return e.errs
}
如何定义自定义异常: APIException
func NewAPIException(code int, msg string) *APIException {
return &APIException{
code: code,
msg: msg,
}
}
// error的自定义实现
type APIException struct {
code int
msg string
}
func (e *APIException) Error() string {
return e.msg
}
func (e *APIException) Code() int {
return e.code
}
// 这个模块定义的业务异常
// token expired %f minitues
// 约定俗成: ErrXXXXX 来进行自定义异常定义, 方便快速在包里搜索
var (
ErrAccessTokenExpired = exception.NewAPIException(5000, "access token expired")
ErrRefreshTokenExpired = exception.NewAPIException(5001, "refresh token expired")
)
if aDelta > 0 {
return ErrAccessTokenExpired.WithMessagef("access token expired %f minutes", aDelta)
}
if e, ok := err.(*exception.APIException); ok {
t.Log(e.String())
// 判断该异常是不是 TokenExpired异常
if e.Code == token.ErrAccessTokenExpired.Code {
t.Log(e.String())
}
}
// exception.IsException(err, token.ErrAccessTokenExpired)
// 给一个异常判断的方法
func IsException(err error, e *APIException) bool {
if targe, ok := err.(*APIException); ok {
return targe.Code == e.Code
}
return false
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。