英文:
Is it possible for function to make a naked return on error in Golang?
问题
我有一组类似这样的结构:
func LoginUser(w http.ResponseWriter, req *http.Request) {
// 在这里进行一些检查
if err != nil {
ReturnErrorResponse(w, errors.LoginError)
return
}
// 在这里进行一些检查
if err != nil {
ReturnErrorResponse(w, errors.BannedUserError)
return
}
// 成功
}
我想知道是否有可能摆脱这些 return,并将它们嵌入到 ReturnErrorResponse 函数中?
因此,如果发生错误,我将返回一个带有错误代码的 JSON 响应,并进行裸返回。
英文:
I have a set of constructs like this:
func LoginUser(w http.ResponseWriter, req *http.Request) {
// do some check here
if err != nil {
ReturnErrorResponse(w, errors.LoginError)
return
}
// do some check here
if err != nil {
ReturnErrorResponse(w, errors.BannedUserError)
return
}
//success
}
I wonder if it's possible to get rid of these returns and somehow embed them into the ReturnErrorResponse function?
So, if an error happens, I return a JSONified response with error code and make a naked return.
答案1
得分: 1
可以通过在ReturnErrorResponse()函数中调用panic()(在发送错误后)来实现,但这既不符合惯用方式,也不高效。
当然,使用panic()需要在延迟函数中调用recover(),可以在一个地方完成,例如在传递给http.ListenAndServe()的“主”处理程序中。
你正在做的是正确的方式。不要使用panic()来处理这个问题。
英文:
It's possible by calling panic() e.g. in your ReturnErrorResponse() function (after sending back the error), but it's neither idiomatic nor efficient.
Using panic() would of course require to call recover() in a deferred function, which could be done in one place, e.g. in a "master" handler passed to http.ListenAndServe().
What you're doing is the proper way. Do not use panic() for this.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论