go: proposal: errors: As with type parameters

Currently in 1.18 and before, when using the errors.As method, an error type you would like to write into must be predeclared before calling the function. For example:

var myErr *MyCustomError
if errors.As(err, &myErr) {
  // handle myErr
}

This can makes control flow around handling errors “unergonomic”.

I’d propose that a new, type parameterized method be added to the errors package in 1.19:

func IsA[T error](err error) (T, bool) {
	var isErr T
	if errors.As(err, &isErr) {
		return isErr, true
	}

	var zero T
	return zero, false
}

This enables more “ergonomic” usage as follows:

err := foo()
if err != nil {
	if myErr, ok := errors.IsA[*MyCustomError](err); ok {
		// handle myErr
	} else if otherErr, ok := errors.IsA[*OtherError](err); ok {
		// handle otherErr
	}

	// handle everything else
}

instead of

err := foo()
if err != nil {
	var myErr *MyCustomError
	if errors.As(err, &myErr) {
		// handle customer error
	}

	var otherErr *OtherError
	if errors.As(err, &otherErr) {
		// handle other error
	}

	// handle everything else
}

This change would reduce the overall LOC needed for handling custom errors, imo improves readability of the function, as well as scopes the errors to the if blocks they are needed in.

Naming is hard so IsA might be better replaced with something else.

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Reactions: 29
  • Comments: 22 (10 by maintainers)

Most upvoted comments

And as noted this doesn’t add any type safety

That’s not quite true: This does add type safety at the language level, rather than leaving it to a go vet check. Under this proposal, this code would not be valid:

type MyError struct{}
func (*MyError) Error() string { return "MyError" }

func main() {
	var err error
	m, ok := errors.AsA[MyError](err) // MyError does not implement error (Error method has pointer receiver)
	fmt.Println(m, ok)
}

The equivalent errors.As call is a run-time panic or go vet failure:

second argument to errors.As must be a non-nil pointer to either a type that implements error, or to any interface type

There are a few benefits of having a generic version of As, that I don’t think have been brought up here. I mentioned them in: https://github.com/golang/go/issues/56949

User @Jorropo wrote the function this way:

func AsOf[E error](err error) (E, bool) {
	var ptrToE *E
	for err != nil {
		if e, ok := err.(E); ok {
			return e, true
		}
		if x, ok := err.(interface{ As(any) bool }); ok {
			if ptrToE == nil {
				ptrToE = new(E)
			}
			if x.As(ptrToE) {
				return *ptrToE, true
			}
		}
		err = Unwrap(err)
	}
	var zero E
	return zero, false
}]

Note that it does not use the current As implementation. The benefits of this implementation are:

  • No usage of reflection
  • No runtime panic possibility
  • An allocation free path
  • Compile time type safety
  • Faster

At first glance this appears to be a breaking change

This would break the following:

var _ = errors.As

@rsc made the case in the original proposal issue that a type-parameterized version of errors.As would not be an improvement: https://github.com/golang/go/issues/29934#issuecomment-490091428

@dsnet also pointed out that the non-type-parameterized version of As can be used in a switch, while the type-parameterized one cannot: https://github.com/golang/go/issues/29934#issuecomment-460093518

I don’t recall if there were any other arguments against a type-parameterized As (aside from, obviously, the fact that type parameters didn’t exist at the time).

I personally think that a type-parameterized As seems fairly reasonable, although the practical benefit over the current As seems small. It would need a good name. I don’t know what that name would be. IsA does not seem right. Under the current design, “Is” is an enhanced form of equality and “As” is an enhanced form of type assertion; blurring that distinction would add confusion.

An argument against adding a type-parameterized As is that the benefit does not justify the cost in API churn and user confusion. I don’t have a strong opinion on whether the benefits do outweigh the costs.

#64629 was closed as duplicate, so let me advertise my idea here. Perhaps, instead of adding new IsA function, it would be easier to add something that actually produces that double pointer? Like this:

func AsTarget[T error](err T) *T {
	p1 := &err
	return p1
}

Then we could:

if errors.As(err, AsTarget(&MyErr{})) {
    ...
}

Love this, I stumbled across this pattern, made a quick blog post about it. Then, of course, that is when I find all the proposals 😂.

I think you can get it down to this terse definition:

func AsA[E error](err error) (e E, _ bool) {
    return e, errors.As(err, &e)
}

Per (closed) duplicate proposal #64771, I advocate for the name errors.Has. Implementation would look like:

// Has returns true if err, or an error in its error tree, matches error type E.
// An error is considered a match by the rules of [errors.As].
func Has[E error](err error) bool {
  return errors.As(err, new(E))
}

CC @jba @neild

(My vague recollection is that this was considered and rejected when errors.As was introduced, even beyond the fact that at the time type parameters did not yet exist.)

A) It’s an Is check, not really an As check, which is less useful. B) That would be very prone to accidental misuse in which the type system would infer error instead of a concrete error type.

This would break the following:

var _ = errors.As

Darn, you are right. I missed that case. Kinda sucks though, because the change would absolutely help with bugs that aren’t discovered until testing or some other runtime occurrence.

All of these proposals are looking for a way to return the error as a specific type, which I agree is nice if possible, but have there been any discussions around simply improving errors.As with generics? Specifically:

func As[T error](err error, target *T) bool {
	// This is used to show the functionality works the same
	return errors.As(err, target)
}

At first glance this appears to be a breaking change, but passing anything that doesn’t meet this criteria into the As function would result in a panic. This change would alert people of the issue sooner (during compile time) rather than at runtime.

It is also very possible I am missing an edge case.

I have looked, but haven’t found an issue that discusses this approach. Please let me know if one exists.