Skip to content

proposal: errors: As with type parameters #51945

Open
@slnt

Description

@slnt

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Proposalerror-handlingLanguage & library change proposals that are about error handling.

    Type

    No type

    Projects

    Status

    Incoming

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions