函数是否有可能在Golang中赤裸裸地返回错误?

函数是否有可能在Golang中赤裸裸地返回错误?

问题描述:

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.

我有一组这样的构造: p>

  func  LoginUser(w http.ResponseWriter,req * http.Request){
 //在这里做一些检查
 err!= nil {
 ReturnErrorResponse(w,errors.LoginError)
 return 
} 
 
  //在这里做一些检查
如果错误!= nil {
 ReturnErrorResponse(w,errors.BannedUserError)
 return 
} 
 
 //成功
} 
  code>  pre>  
 
 

我想知道是否有可能摆脱这些 return code>并将它们嵌入到 ReturnErrorResponse code>函数中? p>

因此,如果发生错误,我将返回带有错误代码的JSON化响应并进行裸返回。 p> div>

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.