proposal: Go 2: add '?' and '!' built-in function names for error handling #42214
Labels
error-handling
Language & library change proposals that are about error handling.
FrozenDueToAge
LanguageChange
Suggested changes to the Go language
Proposal
v2
An incompatible library change
Milestone
I'm proposing adding two built-in functions
?
and!
for better error handling.?
and!
are built-in function names, by default they refer to two functions inerrors
package.?
=errors.Log
!
=errors.Return
You can see the difference from their definitions, that
errors.Log
simply logs the error anderrors.Return
returns a new error.We use
?
or!
whereerr
should place, normally as the last return value receiver from a function call, and they receive theerr
value.can become:
What
!
does here is to receive the last return value(theerr
) fromgetUser(name)
, and iferr != nil
, executeerrors.Return
witherr
as its sole argument and produce a newerr
, then return the outside functionGetUser
with its last return value(error
type) being the newerr
and other return values as what they are. If the value!
receives is nil, nothing will happen.The difference between
?
and!
is that if theerr
value?
receives is not nil, it just executeserrors.Log
for logging butGetUser
goes on, it won't return here.We use
?
and!
to mark that!
will return the outside function if the err value it receives is not nil and?
won't.Customization
Since
?
and!
are built-in function names, they can be assigned to other error handling functions at package or function level.In many cases we want to return a new error that wraps error contexts. We can do that with
!
.We now use
errors.WrapReturn
to return an error handling function and assign it to!
at any time:As you can see, we can assign
!
or?
to our customized error handling functions at package level or function level, at any time. So you can name a package level error handling strategy and override it in a specific function.Summary
This is not a formal Go proposal, I'm not capable of doing that. This is just a new idea for discussion.(Sorry for the proposal title.)
This approach won't meet all error handling scenarios. But it do has some advantages:
if err != nil
common practice, you can combine both when?
or!
is not sufficient.if err != nil { return err }
cases. This is its first goal.if err != nil { return err }
.The text was updated successfully, but these errors were encountered: