doucai6663 2018-05-21 15:40
浏览 235
已采纳

Golang Echo无法在HTTPErrorHandler中使用自定义上下文

e.Use(func(h echo.HandlerFunc) echo.HandlerFunc {
  return func(c echo.Context) error {
    cc := c.(*CustomContext)
    return h(cc)
  }
})


e.HTTPErrorHandler = func(err error, c echo.Context) {
  cc := c.(*CustomContext)
}

I set custom HTTPErrorHandler and CustomContext.

I want to use CustomContext in HTTPErrorHandler.

c.Error(echo.NewHTTPError(http.StatusUnauthorized, "error"))

is work well.

but, panic echo.Context is *echo.context, not *CustomContext error when access not registered page.

Why occurred panic error when access not found page?

  • 写回答

1条回答 默认 最新

  • duandu9260 2018-05-21 15:53
    关注

    The immediate cause of the panic is that the error handler is being called with a "standard" context. To make your type assertion safe, use the two-value form:

    e.HTTPErrorHandler = func(err error, c echo.Context) {
        cc, ok := c.(*CustomContext)
        if ok {
            // A CustomContext was received
        } else {
            // Something else, probably a standard context, was received
        }
    }
    

    But more generally speaking, what you're doing (using a custom context type) is probably a bad idea. If you explain what you're trying to accomplish, there is probably a better, more robust way to solve it.

    One obvious alternative would be to use standard Go contexts, as exposed through echo via c.Request().Context().

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

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!