英文:
How can I avoid the repetition of returning InternalServerError in failure cases?
问题
你可以使用panic函数来中断处理程序的执行。当错误发生时,你可以调用panic函数,它会立即停止当前的执行流程,并开始执行延迟函数(deferred functions)的调用。这样可以确保在中断处理程序之前,所有的清理工作都能得到完成。
你可以将以下代码添加到你的错误处理函数中:
func ErrorHandler(w http.ResponseWriter, err error) {
if err != nil {
http.Error(w, "Internal Server Error", 500)
panic(err) // 中断处理程序的执行
}
}
当panic函数被调用时,它会停止当前的执行流程,并开始执行延迟函数的调用。如果没有被捕获或处理,panic会导致程序崩溃并输出错误信息。你可以在调用panic时传递错误对象,以便在程序崩溃时输出相关的错误信息。
请注意,使用panic函数会中断整个处理程序的执行,因此你需要确保在适当的地方进行错误处理,以避免不必要的中断。
英文:
I'm trying to add a function for error handling to my web app and instead of doing this all the time
if err != nil {
http.Error(w, "Internal Server Error", 500)
return
}
do something like this :
ErrorHandler(err)
I made this function :
func ErrorHandler(w *http.ResponseWriter, err error) {
if err != nil {
http.Error(*w, "Internal Server Error", 500)
// break the go routine
}
}
but i don't know how can i break the handler when error occurs
答案1
得分: 0
当发生错误时,你不能中断处理程序。有几种方法可以干净地处理这个问题,但第一种选择(使用http.Error)也是相当不错的。
一种选择是将处理程序编写为:
func Handler(w http.ResponseWriter, req *http.Request) {
err := func() error {
// 做一些操作
if err != nil {
return err
}
return nil
}()
if err != nil {
http.Error(w, "内部服务器错误", 500)
}
}
另一种选择是使用类似中间件的模式:
func CheckError(hnd func(http.ResponseWriter, *http.Request) error) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, req *http.Request) {
err := hnd(w, req)
if err != nil {
// 在这里处理错误
}
}
}
然后你可以将其用作处理程序:
CheckError(handler)
其中
func handler(w http.ResponseWriter, req *http.Request) error {
}
英文:
You can't break the handler when an error occurs. There are ways to do this cleanly, but the first option (using http.Error) is pretty good as well.
One option is to write the handler as:
func Handler(w http.ResponseWriter, req *http.Request) {
err:=func() {
// Do stuff
if err!=nil {
return err
}
}()
if err!=nil {
http.Error(w, "Internal Server Error", 500)
}
}
Another option is to use a middleware-like pattern:
func CheckError(hnd func(http.ResponseWriter,*http.Request) error) func(http.ResponseWriter,*http.Request) {
return func(w http.ResponseWriter, req *http.Request) {
err:=hnd(w,req)
if err!=nil {
// Deal with the error here
}
}
}
Then you can use this as a handler:
CheckError(handler)
where
func handler(w http.ResponseWriter, req *http.Request) error {
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论