I cannot find a good confirmation if returning both non-nil value and non-nil error at the same time is conventional or not. Example:
func makeHTTPCall(...) string, error {
resp, err := http.Post(...)
if err != nil {
return "", err
}
var r string
if resp.StatusCode == http.StatusOK {
if err := json.NewDecoder(resp.Body).Decode(&r); err != nil {
return "", err
}
if err := resp.Body.Close(); err != nil {
// should I return error here even if I have successful result?
// or should I return both non-nil value and non-nil error?
// or should i just log the error?
}
return r, nil
}
}
Definitely it is allowed by compiler. Why I'm asking is because of the convention to check for error first. If I return both non-nil value and error client code will do the check for error first and will go on error handling path:
str, err := makeHTTPCall(...)
if err != nil {
throw err
}
Is there any agreement around this?
erris non-nil, the other return value should be treated as undefined unless very well documented. Even if documented, I think that's a code smell -- a sign that you need to break up the function into smaller pieces whose errors can be handled separately.