Golang. How to handle errors from http.HandleFunc?

huangapple go评论62阅读模式
英文:

Golang. How to handle errors from http.HandleFunc?

问题

我对路由进行了一些封装。

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

如果在我的处理程序(mainHandler、saveHandler)中发生了错误,我能否以某种方式获取它?我想将该错误进一步返回并进行分析,例如:

err := MainInitHandlers

这种做法可行吗?

英文:

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?

答案1

得分: 2

这些函数无法返回错误,并且它们在你尝试使用返回值的地方被调用,只注册为处理程序。因此,不能从它们那里获取错误信息。在处理HTTP请求时,你可能会遇到的错误类型应该在处理程序函数内部处理,通常是通过向客户端返回错误代码并发出某种日志消息或警报,以供开发人员响应。

英文:

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.

答案2

得分: 1

你可以始终编写一个包装器:

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

你可以编写一个包装器函数 wrap,它接受一个 withError 类型的函数作为参数,并返回一个 http.Handler。在包装器函数内部,它创建了一个 http.HandlerFunc,并在其中调用了传入的函数 f。然后,它使用 http.Handle 将包装后的处理程序注册到默认的路由路径上。

英文:

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

huangapple
  • 本文由 发表于 2022年11月26日 03:23:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/74577162.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定