-
-
Notifications
You must be signed in to change notification settings - Fork 832
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: Ergonomic error returns #302
Comments
this really needs "lazy" syntax. There's a huge thread about this here: golang/go#37739 basically, the problem you'll run into when developing something like this, is that you essentially want to wait to evaluate something (like the error string, especially in the case of using |
but, there's a bit of a work around today (though without caching behavior) simply be func ReturnWrapped[T any](x T, err error, info string) (T, error) { it would be:
The function signature could be more flexible as well, to work both with func ReturnWrapped[T any](x T, err error, msgAndArgs ...func() any) (T, error) { in this way: switch l := len(msgAndArgs); {
case l == 0:
return errors.WithStack(err)
case l == 1:
return errors.Wrap(err, string(msgAndArgs[0]()))
default:
msg := msgAndArgs[0]
args := msgAndArgs[1:]
argsAsAny := lo.Map(args, // more here)
return errors.Wrapf(err, string(msg()), argsAsAny...)
} or something to this effect inspiration from
|
I think there's a little bit of confusion here about Go typing. Assuming that a generic helper like There are a few ways to work around that kind of thing with generics, depending on what kinds of use cases you want to support. If you only ever want this to work with pointer types, then that's easy: just change the signature to func Return[T any](x T, err error) (T, error) {
if err != nil {
var zeroValue T
return zeroValue, err
}
return x, nil
} The part with Now— is this function useful? It depends on what you're trying to accomplish. The only difference between your original example and simply writing But if there's a reason why you need to do so, and you do it often enough that a generic helper would be useful, I would definitely recommend naming it something more specific. The only thing that this helper is doing that is different from a plain |
I actually just realized something. If you are using |
From a memory management standpoint, discardOnError does seem useful. I don't think that's what the complaint was though. |
A common pattern I've seen in code is this:
and this
Would something like this:
and one with wrapping
be a good addition?
That woud simplify the previous cases to:
and
I understand that using
lo.Ternary
would already make this a one liner, but that would still introduce a lot of repeated behaviour (swapping the parameters, wrapping the error).The text was updated successfully, but these errors were encountered: