dsyrdwdbo47282676 2016-09-02 05:41
浏览 83
已采纳

中间件错误处理

I have a chain of claw http.Handler middlewares, where my first handler might write an error response:

http.Error(w, err.Error(), http.StatusUnauthorized)

However my other middlewares continue executing, but I don't want it to. What is the best way to go about this? I tried checking the status header after calling http.Error(), to see if it is other than a 200:

status := w.Header().Get("Status")

but status is an empty string.

  • 写回答

1条回答 默认 最新

  • duanbangzhou7809 2016-09-02 08:26
    关注

    You can use a "naked" return just after your error to stop the middleware chain execution.

    From http documentation:

    Error replies to the request with the specified error message and HTTP code. It does not otherwise end the request; the caller should ensure no further writes are done to w. The error message should be plain text.

    From this Custom Handlers and Avoiding Globals in Go Web Applications :

    func myHandler(w http.ResponseWriter, r *http.Request) {
        session, err := store.Get(r, "myapp")
        if err != nil {
            http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
            return // Forget to return, and the handler will continue on
        }
        .../...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?