Golang. How to handle errors from http.HandleFunc?

918 Views Asked by At

I made some wrapping aroung routing

func (p Page) MainInitHandlers() {
  http.HandleFunc("/", p.mainHandler)
  http.HandleFunc("/save", p.saveHandler)
}

If something wrong will happen inside my hadlers (mainHandler, saveHandler), can I get it somehow? I want to return that error further and analyze like

err := MainInitHandlers

It it possible?

2

There are 2 best solutions below

3
user229044 On

Those functions cannot return errors, and they are invoked at the point you're trying to consume a return value, only registered as handlers. So no, you cannot get error information out of them. The types of errors you're likely to encounter while handling an HTTP request should be handled within the handler function, typically by returning an error code to the client and emitting some kind of log message or alert for your developers to respond to.

0
Steve D On

You can always write a wrapper:

type withError func(ctx context.Context, r *http.Request, w http.ResponseWriter) error

func wrap(f withError) http.Handler {
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    processErr(f(r.Context(), r, w))
  })
}

http.Handle("", wrap(...))