gpt4 book ai didi

google-app-engine - 是否有可能从谷歌应用引擎的 panic 中恢复过来?

转载 作者:IT王子 更新时间:2023-10-29 02:16:17 25 4
gpt4 key购买 nike

我想知道是否有可能从 panic 中恢复过来。似乎 GAE 有它自己的 panic recovery机制,但我找不到任何 Hook 来处理我的应用程序。

最佳答案

AppEngine 网络应用程序中的处理程序以与普通 Go 应用程序相同的方式注册。您不必显式调用 http.ListenAndServe()(因为它将由平台调用),并且处理程序注册发生在 init() 函数中(不是在 main()).

话虽如此,同样的 panic-recover 包装也适用于 AppEngine,不幸的是没有其他更好的方法。

看看这个例子:它使用了一个用 HandleFunc() 注册的函数和一个 Handler注册 Handle()处理 2 个 URL 模式,但都故意 panic (他们拒绝服务):

func myHandleFunc(w http.ResponseWriter, r *http.Request) {
panic("I'm myHandlerFunc and I refuse to serve!")
}

type MyHandler int

func (m *MyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
panic("I'm MyHandler and I refuse to serve!")
}

func main() {
http.HandleFunc("/myfunc", myHandleFunc)
http.Handle("/myhandler", new(MyHandler))

panic(http.ListenAndServe(":8080", nil))
}

将浏览器指向 http://localhost:8080/myfunchttp://localhost:8080/myhandler 会导致 HTTP 500 状态:内部服务器错误 (或空响应,具体取决于您检查它的位置)。

一般的想法是使用recover 来“捕捉”来自处理程序的 panic (spec: Handling panics)。我们可以通过首先注册 defer 的方式“包装”句柄函数或处理程序。即使函数的其余部分发生 panic 也会调用该语句,并且我们从 panic 状态中恢复过来。

查看这两个函数:

func protectFunc(hf func(http.ResponseWriter,
*http.Request)) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
defer func() {
r := recover()
if r != nil {
// hf() paniced, we just recovered from it.
// Handle error somehow, serve custom error page.
w.Write([]byte("Something went bad but I recovered and sent this!"))
}
}()
hf(w, r)
}
}

func protectHandler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
r := recover()
if r != nil {
// h.ServeHTTP() paniced, we just recovered from it.
// Handle error somehow, serve custom error page.
w.Write([]byte("Something went bad but I recovered and sent this!"))
}
}()
h.ServeHTTP(w, r)
})
}

第一个接受一个函数并返回一个调用我们传递的函数的函数,但如果一个函数被启动,它会从 panic 状态中恢复。

第二个接受一个 Handler 并返回另一个 Handler,它同样调用传递的那个,但也处理 panic 并恢复正常执行。

现在如果我们注册处理函数和受这些方法保护的Handler,注册的处理函数将永远不会崩溃(假设恢复正常执行后的代码不会崩溃):

http.HandleFunc("/myfunc-protected", protectFunc(myHandleFunc))
http.Handle("/myhandler-protected", protectHandler(new(MyHandler)))

访问 http://localhost:8080/myfunc-protectedhttp://localhost:8080/myhandler-protected URL 导致 HTTP 200 状态(正常)带有消息:

Something went bad but I recovered and sent this!

关于google-app-engine - 是否有可能从谷歌应用引擎的 panic 中恢复过来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28815334/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com