如何避免在失败情况下重复返回 InternalServerError?

问题描述

我正在尝试向我的网络应用程序添加一个错误处理函数,而不是一直这样做

if err != nil {
   http.Error(w,"Internal Server Error",500)
   return
}

做这样的事情:

ErrorHandler(err)

我做了这个功能

func ErrorHandler(w *http.ResponseWriter,err error) {
    if err != nil {
        http.Error(*w,500)
        // break the go routine
    }
}

但我不知道如何在发生错误时中断处理程序

解决方法

发生错误时不能中断处理程序。有很多方法可以做到这一点,但第一个选项(使用 http.Error)也很不错。

一种选择是将处理程序编写为:

func Handler(w http.ResponseWriter,req *http.Request) {
    err:=func() {
       // Do stuff
       if err!=nil {
         return err
       }
    }()
    if err!=nil {
       http.Error(w,"Internal Server Error",500)
    }
}

另一种选择是使用类似中间件的模式:

func CheckError(hnd func(http.ResponseWriter,*http.Request) error) func(http.ResponseWriter,*http.Request) {
   return func(w http.ResponseWriter,req *http.Request) {
      err:=hnd(w,req)
      if err!=nil {
         // Deal with the error here
      }
    }
}

然后您可以将其用作处理程序:

CheckError(handler)

哪里

func handler(w http.ResponseWriter,req *http.Request) error {
}