-1

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?

Kroning
  • 19
  • 2
  • 1
    `http.HandleFunc` only registers the arguments, it does not execute them, therefore it returns before anything can go wrong within those registered handlers. If you by mistake happen to register multiple handlers under the same pattern the `http.HandleFunc` will panic. – mkopriva Nov 25 '22 at 19:27
  • 1
    If a handler encounters an error it usually reports that to the client through the `http.ResponseWriter` argument. However if you want to centralise error handling you can use "middleware" for that. https://go.dev/play/p/cK1tvGbsp75 – mkopriva Nov 25 '22 at 19:29

2 Answers2

2

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.

user229044
  • 232,980
  • 40
  • 330
  • 338
  • So, app will start without errors, and I can only use "log" and "http.Error" to monitor that everything is fine? – Kroning Nov 25 '22 at 22:11
  • 2
    @Kroning errors are just values; you can do whatever you want with them. If you want to monitor them externally, logging is a good way to go. If you want something more internal, you can send them on a channel. – Hymns For Disco Nov 25 '22 at 22:26
  • @HymnsForDisco, yes, I know. Chans, actually, is a very interesting idea. Thanks! – Kroning Nov 25 '22 at 22:51
1

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(...))
Steve D
  • 373
  • 2
  • 17