proposal: Go 2: error handling with magic .handleErr() method #56126
Labels
error-handling
Language & library change proposals that are about error handling.
FrozenDueToAge
LanguageChange
Suggested changes to the Go language
Proposal
Proposal-FinalCommentPeriod
v2
An incompatible library change
Milestone
Author background
Related proposals
Proposal
What is the proposed change?
I propose to add a new method which can be named
handleErr
,unwrap
orexpect
or to any function operation that may return a value and an error or just an error. Currently error handling feels very repetitive in many cases. After using a function we need to add about 3 lines of code to testif err != nil
. What I am proposing would allow us to accomplish the same but with less code. I am not proposing to replace the existing error handling but to enhance it.I have been inspired by the same functionality that is available in Rust.
Who does this proposal help, and why?
It helps to handle errors with less code.
Please describe as precisely as possible the change to the language.
We would enhance the existing error handling mechanism by adding special functions which are evaluated at compile time and have the compiler either add code for us (add the classic if statements we would add) or exit the enclosing function's execution while simulating the same thing that happens when we manually return the error.
Another example is when the function is supposed to return a value and an error
Costs
Would this change make Go easier or harder to learn, and why?
I think it would make Go more enjoyable, specially around the error handling area.
In Go we are expected to treat "Expected Errors" as error values (sentinel errors) and "Unexpected errors/Exceptions" as Error Types but we incur in a lot of
IF
statement repetitions to accomplish error handling. What I am proposing is to de-load the usage ofif statements
to check errors and return them and have a special way of dealing with that so we useIF
statements to check application logic rather than both (logic and error handling).Implementation tips
As the first pass, we can have the compiler write the if statement for us when encounters a function call followed by a call to one of the special functions. Just like we do with the * and pointers. Then, in a future implementation a more comprehensive approach could be implemented.
The text was updated successfully, but these errors were encountered: