【Golang】如何統一處理HTTP請求中的異常捕獲

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

最近寫GOLANG項目,不使用架構,路由選擇httprouter
現在想實現一個需求:在不修改httprouter源碼的前提下,對所有註冊的路由handle進行異常捕獲。

大家都知道golang使用panic()產生異常,然後可以recover()來捕獲到異常,否則主程式直接宕掉,這是我們不希望看到的。
或者全程檢查error,不主動拋出異常。即便這樣,可能異常依然不能避免。

既然要recover(),但又不想在每個handle裡面都去recover()一遍,如果你也有這樣的需求,下面講到的可能對你有用。

func RegRouters(r *httprouter.Router) {    r.GET("/", Home)    r.GET("/contact", Contact)}func Home(w http.ResponseWriter, r *http.Request, params httprouter.Params) {    defer func() {            if pr := recover(); pr != nil {                fmt.Printf("panic recover: %v\r\n", pr)                debug.PrintStack()            }        }()    //something}func Contact(w http.ResponseWriter, r *http.Request, params httprouter.Params) {    defer func() {            if pr := recover(); pr != nil {                fmt.Printf("panic recover: %v\r\n", pr)                debug.PrintStack()            }        }()    //something}

正常的路由表長這樣。在C#中相當於對每個請求加try...catch,將業務上程式碼封裝裹起來。
可能你已經想到了,對,包裹起來,像這樣:

func RegRouters(r *httprouter.Router) {    r.GET("/", WrapHandle(Home))    r.GET("/contact", WrapHandle(Contact))}

那這個wrap方法長什麼樣呢?他需要有一個handle類型的參數,同時傳回值要能被httprouter接收,直接上代碼

func WrapHandle(handle httprouter.Handle) httprouter.Handle {    return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {        defer func() {            if pr := recover(); pr != nil {                fmt.Printf("panic recover: %v\r\n", pr)                debug.PrintStack()            }        }()        handle(w, r, p)    }}

是不是很簡單~ 我們再改造一下,加一個上下文,把handle簡化一下

func WrapHandle(handle func(ctx *context.Context)) httprouter.Handle {    return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {        defer func() {            if pr := recover(); pr != nil {                fmt.Println("panic recover: %v", pr)                debug.PrintStack()            }        }()        ctx := context.NewContext(w, r, p)        handle(ctx)    }}func Home(ctx *context.Context) {    defer func() {            if pr := recover(); pr != nil {                fmt.Printf("panic recover: %v\r\n", pr)                debug.PrintStack()            }        }()    //something}func Contact(ctx *context.Context) {    defer func() {            if pr := recover(); pr != nil {                fmt.Printf("panic recover: %v\r\n", pr)                debug.PrintStack()            }        }()    //something    id = ctx.FormInt64("id") //通過context從FORM取值,並轉換為int64}

看出有什麼不同了嗎?對,多了一個context包,handle的參數也減少到一個,主要是context上可以做更多的事情。

一個簡單的請求內容相關的原型:

type Context struct {    responseWriter http.ResponseWriter    request        *http.Request    params         httprouter.Params    Data           map[string]interface{}}func NewContext(w http.ResponseWriter, r *http.Request, params httprouter.Params) *Context {    ctx := new(Context)    ctx.responseWriter = w    ctx.request = r    ctx.params = params    ctx.Data = make(map[string]interface{})    return ctx}func (ctx *Context) FormValue(name string) string {    return ctx.request.FormValue(name)}func (ctx *Context) FormInt64(name string) int64 {    value, _ := strconv.ParseInt(ctx.FormValue(name), 10, 64)    return value}//更多擴充....

好了,先到這裡,希望對你有協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.