dongqian0763 2018-10-26 05:38
浏览 189

错误处理中间件-将err转换为字符串以进行响应

I have this middleware func:

func errorMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        defer func() {
            if err := recover(); err != nil {
                log.Error("Caught error in defer/recover middleware: ", err)
                w.WriteHeader(http.StatusInternalServerError)
                json.NewEncoder(w).Encode(struct {
                    ID string
                }{
                    err.Error(),
                })
            }
        }()
        next.ServeHTTP(w, r)
    })
}

I use it like so:

router := mux.NewRouter()
router.Use(errorMiddleware)

however I am getting a compilation error, it says:

enter image description here

Anybody know what that's about? I am just trying to convert err to a string, ultimately, serialize it for the client etc.

  • 写回答

1条回答 默认 最新

  • dongyou9721 2018-10-26 05:55
    关注

    recover() returns an interface with no methods to proxy any value sent by panic(). In the defer block, you're trying to access the Error() method of a pure, has-no-method interface. If you want to distinguish the built-in error type, you'd have to assert its type like:

    realErr, ok := err.(error)
    if ok {
        // here you can use realErr.Error().
    }
    

    So that it'll give you a real value of type error. If you check out the built-in types, you'll see that error is to implement an Error() string method.

    Type assertions: https://tour.golang.org/methods/15

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度