How to work correctly with refactor error handling?

I'm just starting out with Go, so I'm still not used to its templates.

I have a web server that serves as a proxy for other remote services. I use muxapp engine to map routes to handlers.

// imports ommited.

func init() {
  m = mux.NewRouter()
  m.HandleFunc("/ponies", listPonies)
  m.HandleFunc("/rainbows", listRainbows)
  http.Handle("/", m)
}

func listPonies(w http.ResponseWriter, r *http.Request) {
  ponies, err := ponyService.getAll()

  if err != nil {
      w.write(err.Error())
      return;
  }

  w.write(string(ponies))
}

func listRainbows(w http.ResponseWriter, r *http.Request) {
  rainbows, err := rainbowService.getAll()

  if err != nil {
      w.write(err.Error())
      return;
  }

  w.write(string(rainbows))
}

I would like to reorganize the general code (error handling, conversion to string and recording response) into one function.

My first attempt was to simply define a generic function to call:

func handleErrorAndWriteResponse(w http.ResponseWriter, obj Stringer, err error) {
  if err != nil {
      w.write(err.Error())
      return;
  }

  w.write(string(obj))
}

And call it that

func listPonies(w http.ResponseWriter, r *http.Request) {
  handleErrorAndWriteResponse(w, ponyService.getAll())       
}

func listRainbows(w http.ResponseWriter, r *http.Request) {
  handleErrorAndWriteResponse(w, rainbowService.getAll())
}

But

  • This does not work. I get an error insufficient arguments. This is probably due to the confusion of several response values ​​from services that are not directly translated into the arguments of the called function.
  • . , , . , Go.

" " ( "Go" )?

+3
1

golang.org , AppEngine. , " ".

, error , :

type appHandler func(http.ResponseWriter, *http.Request) error

func (fn appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    if err := fn(w, r); err != nil {
        http.Error(w, err.Error(), 500)
    }
}

func listPonies(w http.ResponseWriter, r *http.Request) error {
    ponies, err := ponyService.getAll()

    if err != nil {
        return err;
    }

    w.write(string(ponies))
}

-:

func init() {
    http.Handle("/view", appHandler(listPonies))
}
+4

All Articles