Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I argue that errors.Wrap and errors.Is from the Go stdlib solves this problem. Libraries can export their own error types and you can check if they threw that error type. I use this pattern all the time to handle special errors differently. Used it to implement optimistic locking which does ~not~ simply propagate all errors upwards!

https://gosamples.dev/check-error-type/

  cond, err := foo()
  if errors.Is(err, ErrFooHadTemporaryFailure) {
    // retry
  } else if errors.Is(err, ErrFooHostOffline) {
    // switchFooHost() 
  } else if err != nil {
    // propagate unhandled error upwards
    return nil, fmt.Errorf("foo unhandled err: %w", err)
  }

Of course it is up to the package author (or yourself) to write functions that return specific wrapped error types. Otherwise we're stuck in the situation your comment describes.

What do you mean by creating an error interface? It's a one liner to make a new error case:

  var ErrFooHadTemporaryFailure = errors.New("temporarily failure, retry later")


Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: