Home > Enterprise >  Golang. How to handle errors from http.HandleFunc?
Golang. How to handle errors from http.HandleFunc?

Time:11-26

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?

CodePudding user response:

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.

CodePudding user response:

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(...))
  • Related