dongyuluan7494 2019-03-06 20:15
浏览 39
已采纳

从多重错误类型检测特定错误

Trying to differentiate from a bad user-cookie error vs. an internal error using gorilla/sessions e.g.

import "github.com/gorilla/sessions"

sess, err := store.Get(r, sessName)
if err != nil {
    // either user error (bad-cookie i.e. invalid HMAC)
    //      http.Error(w, "not authenticated", http.StatusUnauthorized)

    // or server error (FileSystemStore i/o)
    //      http.Error(w, "internal error", http.StatusInternalServerError)
    return
}

The underlying securecookie package has an exported error ErrMacInvalid for bad user cookies. So ordinarily one would just check for this specific error, but this does not work:

import "github.com/gorilla/securecookie"

if err == securecookie.ErrMacInvalid {
    // bad user-cookie
} else if err != nil {
    // otherwise internal error
}

The reason it does not work - using say securecookie.NewCookieStore() as a session store - is it will return a error of type securecookie.MultiError (a []error type) with the securecookie.ErrMacInvalid value listed within the error slice.

Trying something like this seems very convoluted:

if e2, ok := err.(securecookie.MultiError); ok && len(e2) > 0 && e2[0] == securecookie.ErrMacInvalid { {
    // bad user-cookie
} else if err != nil {
    // otherwise internal error
}

is there an easier way?

  • 写回答

1条回答 默认 最新

  • dongpao5261 2019-03-06 20:26
    关注

    is there an easier way?

    No. Sorry.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何使用simulink建立一个永磁同步直线电机模型?
  • ¥30 天体光谱图的的绘制并得到星表
  • ¥15 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗