xerrors 快速panic错误

xerrors用法

image-20200805103921467

return errors.Forbidden(xconfig.ServiceName + ":addSubchannelAdmins", "权限不足")
=>
xerrors.PanicForbidden("权限不足")

return errors.BadRequest(xconfig.ServiceName + ":addSubchannelAdmins", "重复创建频道协管")
=>
xerrors.PanicBadRequest("重复创建频道协管")

效果:

{"id":"ChannelService.UpdateChannelNickname beenest/channel-srv/handler:42","code":403,"detail":"没有权限","status":"Forbidden"}

id的默认组成:服务名.当前方法名 文件路径:行数

组件背景

  • 常规处理:
func (h *ChannelHandler) addSubchannelAdmins(
    ctx context.Context,
    userIDs []int64,
    subchannelIDs []int64,
    adminTypeToAdd commonPb.AdminType,
    currentUser int64,
) error {
    uids := userIDs
    sids := subchannelIDs
    // 校验操作者的权限
    ...
    if adminTypeToAdd == commonPb.AdminType_subchannelAdmin {
        // owner、超级管理员可以添加子频道管理
        if isOwner || isSuperAdmin {
            ...
      if alreadyExists {
        return errors.BadRequest("", "重复创建频道管理")
      }
        } else {
            return errors.Forbidden(xconfig.ServiceName + ":addSubchannelAdmins", "权限不足")
        }
    } else {
        adminTypeCurrent, err := h.repo.SubchannelAdminGetType(ctx, currentUser, subchannelIDs[0])
        global.AssertError(ctx, err)
        // owner、频道管理员、子频道管理可以创建子频道协管
        if isOwner || isSuperAdmin || adminTypeCurrent == enum.AdminSubchannelAdmin {
            ...
      if alreadyExists {
        return errors.BadRequest("", "重复创建频道管理")
      }
        } else {
            return errors.Forbidden(xconfig.ServiceName + ":addSubchannelAdmins", "权限不足")
        }
    }
    return nil
}

上面代码有两个问题:

  • 直接return,这样日志会丢失堆栈,不知道是哪行return的错误
  • errors.BadRequest(id, msg),id写法繁琐,也容易偷懒不写
Copyright © xinyan all right reserved,powered by Gitbook该文件修订时间: 2020-08-05 10:40:06

results matching ""

    No results matching ""