Skip to content
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: errors: In() to check Is against multiple errors #70961

Open
koaim opened this issue Dec 22, 2024 · 3 comments
Open

proposal: errors: In() to check Is against multiple errors #70961

koaim opened this issue Dec 22, 2024 · 3 comments
Labels
Milestone

Comments

@koaim
Copy link

koaim commented Dec 22, 2024

Proposal Details

Problem
The code looks redundant and cumbersome in cases when you need to check an error match several times. Example:

func foo() {
  err := bar()
  if errors.Is(err, err1) || errors.Is(err, err2) || errors.Is(err, err3) {
    // some logic
  }
}

Solution
A new function that will allow you to check for errors like this:

func foo() {
  err := bar()
  if errors.In(err, err1, err2, err3) {
    // some logic
  }
}

Implementation

package errors

func In(err error, target ...error) bool {
  for _, v := range target {
    if errors.Is(err, v) {
      return true
    }
  }

  return false
}
@koaim koaim added the Proposal label Dec 22, 2024
@gopherbot gopherbot added this to the Proposal milestone Dec 22, 2024
@seankhliao seankhliao changed the title proposal: errors: new function errors.In() proposal: errors: In() to check Is against multiple errors Dec 22, 2024
@seankhliao
Copy link
Member

I don't think it's a very common thing to do:
https://github.com/search?q=language%3AGo+%2F%28errors.Is.*%5C%7C%5C%7C%29%2B%2F&type=code

@ianlancetaylor ianlancetaylor moved this to Incoming in Proposals Dec 22, 2024
@zigo101
Copy link

zigo101 commented Dec 23, 2024

How about

// Match returns the matched error in targets for err.
func Match(err error, targets ...error) error 

?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
Status: Incoming
Development

No branches or pull requests

5 participants