-
Notifications
You must be signed in to change notification settings - Fork 17.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
proposal: "reflow" keyword for error handling #21146
Comments
How about something like this: func MyFunction() (string, error) {
data, err := doSomething() return nil, err
...
doAnotherThing(data)
return data, nil
} Another example: func ReadFile(path string) ([]byte, error) {
f, err := os.Open(path)
if err != nil {
return nil, errors.Wrap(err, "open failed")
}
defer f.Close()
buf, err := ioutil.ReadAll(f)
if err != nil {
return nil, errors.Wrap(err, "read failed")
}
return buf, nil
} becomes func ReadFile(path string) ([]byte, error) {
f, err := os.Open(path) return nil, errors.Wrap(err, "open failed")
defer f.Close()
buf, err := ioutil.ReadAll(f) return nil, errors.Wrap(err, "read failed")
return buf, nil
} Maybe we could omit some tokens making them inferred func ReadFile(path string) ([]byte, error) {
f := os.Open(path) return errors.Wrap(err, "open failed")
defer f.Close()
buf := ioutil.ReadAll(f) return errors.Wrap(err, "read failed")
return buf, nil
} |
what about this func ReadFile(path string) ([]byte, error) {
f, err := os.Open(path) !! return nil, errors.Wrap(err, "open failed")
defer f.Close()
buf, err := ioutil.ReadAll(f) !! return nil, errors.Wrap(err, "read failed")
return buf, nil
} The !! operator indicates what to do if the operation fails, and the variables on the left side are accessible on the right side, although this could make the lines longer. |
I don't think my idea is a good idea at all, but I'm just throwing it here as an idea. err := doSomething()
(err != nil) ?! : return err By the way, you can do ```go for Go syntax highlighting on Github. |
This idea does not address the main issue discussed in #21161, which is to provide a simpler mechanism for wrapping an error as appropriate. This only simplifies returning an existing error, not wrapping it. Closing in favor of a general Go 2 rethink of error handling. |
I would like to propose a new keyword "reflow".
This keyword acts as "return" only if the last value to return is not nil, otherwise it does nothing and execution of function goes on.
It can be very helpful to return values along with an error without having to write an if statement to check that the error is not nil every time.
It replaces a function like this:
in a more concise way:
Practically, the reflow keyword returns from function only if the last argument is not nil.
The text was updated successfully, but these errors were encountered: