News for hackers. Stuff that matters.
Re:Gopher Wrangling. Effective error handling in Go by simiones on Wednesday June 21, 2023 @04:53AM (#36416084)
If your original error is `fmt.Errorf("failed to frobulate")` or even `errors.New("failed to frobulate")`, even if it's bubbled up with `fmt.Errorf("foo() failed: %w", err)`, errors.Is and errors.As are useless for checking it (each error in the chain, including the original, will be a new instance of fmt.stringError or something like that).

This is equivalent to the problem of throwing new Exception("some message") or new RuntimeException("some message") in Java, to be fair. But this is more rarely done there in my experience, especially because people are more used to defining new exception types since the stdlib has many examples of that, unlike Go (which all returns `error` for all error types).

Re:Gopher Wrangling. Effective error handling in Go by philosopher1234 on Wednesday June 21, 2023 @01:11PM (#36421368)
Re:Gopher Wrangling. Effective error handling in Go by simiones on Thursday June 22, 2023 @05:17AM (#36429708)
That's not how people commonly use errors, with global variables.

The way code usually looks like is this:

  func foo(arg int) error {
    if arg < 0 {
      return fmt.Errorf("expected >0, got %d", arg)
    }
    if arg > 8 {
      return fmt.Errorf("expected >8, got %d", arg)
    }
    //do stuff
  }
or

  func foo(arg int) error {
    if arg < 0 {
      return errors.New(fmt.Sprintf("expected >0, got %d", arg))
    }
    if arg > 8 {
      return errors.New(fmt.Sprintf("expected >8, got %d", arg))
    }
    //do stuff
  }
In either of these cases, a caller of foo() can at best parse err.String() to see why foo() complained. But there is no way that errors.As or errors.Is help with the majority of errors returned by Go programs.
Re:Gopher Wrangling. Effective error handling in Go by Ajnasz on Thursday June 22, 2023 @08:47AM (#36431312)
I guess it's the same in most of languages. If you raise a general exception with a custom message you'll have to check the message not it's type.
Re:Gopher Wrangling. Effective error handling in Go by throwaway894345 on Thursday June 22, 2023 @09:54PM (#36441877)
That’s not the fault of fmt.Errorf(); if you aren’t giving people a type or a value to compare against there’s nothing the standard library can do to help you. You need to try string matching or maybe reflection. The standard library can’t fix bad code. Thankfully I don’t share your experience with people commonly returning those kinds of errors (at least not where one needs to match against an error).