【问题标题】:How can I avoid the repetition of returning InternalServerError in failure cases? [duplicate]如何避免在失败情况下重复返回 InternalServerError? [复制]
【发布时间】:2021-09-03 12:13:12
【问题描述】:

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

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, "Internal Server Error", 500)
        // break the go routine
    }
}

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

【问题讨论】:

    标签: go error-handling http-status-codes code-duplication go-http


    【解决方案1】:

    发生错误时,您不能中断处理程序。有很多方法可以干净地做到这一点,但第一个选项(使用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 {
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-17
      • 1970-01-01
      • 2013-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-17
      • 1970-01-01
      相关资源
      最近更新 更多