在Golang中,函数是否可以在错误发生时进行裸返回?

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

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.

huangapple
  • 本文由 发表于 2016年11月22日 20:51:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/40742371.html
匿名

发表评论

匿名网友

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

确定