Search code examples
goerror-handlinghttp-status-codescode-duplicationgo-http

How can I avoid the repetition of returning InternalServerError in failure cases?


I'm trying to add a function for error handling to my web app and instead of doing this all the time

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

do something like this :

ErrorHandler(err)

I made this function :

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

but i don't know how can i break the handler when error occurs


Solution

  • You can't break the handler when an error occurs. There are ways to do this cleanly, but the first option (using http.Error) is pretty good as well.

    One option is to write the handler as:

    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)
        }
    }
    

    Another option is to use a middleware-like pattern:

    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
          }
        }
    }
    

    Then you can use this as a handler:

    CheckError(handler)
    

    where

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