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.
Currently in 1.18 and before, when using the
errors.Asmethod, an error type you would like to write into must be predeclared before calling the function. For example:This can makes control flow around handling errors "unergonomic".
I'd propose that a new, type parameterized method be added to the
errorspackage in 1.19:This enables more "ergonomic" usage as follows:
instead of
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
ifblocks they are needed in.Naming is hard so
IsAmight be better replaced with something else.