m-lab / go

General purpose libraries / APIs for use in mlab code.
Apache License 2.0
5 stars 6 forks source link

Add rtx.ErrorLoggingCloser to wrap Close() and log errors. #30

Closed robertodauria closed 5 years ago

robertodauria commented 5 years ago

Discussed with @stephen-soltesz during a call. This might be useful to simplify some code where we want to not ignore the error returned by a deferred call.


This change is Reviewable

coveralls commented 5 years ago

Pull Request Test Coverage Report for Build 329


Totals Coverage Status
Change from base Build 313: 0.5%
Covered Lines: 408
Relevant Lines: 566

💛 - Coveralls
pboothe commented 5 years ago

Could also do:

/*interface Closer {
  func Close() error
}
*/

struct errorLoggingCloser {
  c io.Closer
}

func (elc *errorLoggingCloser) Close() error {
  err := elc.c.Close()
  if err != nil {
    log.Println(err)
  }
  return err
}

func ErrorLoggingCloser(c Closer) Closer {
  return errorLoggingCloser{c}
}

then this could be used like:

defer ErrorLoggingCloser(f).Close()
pboothe commented 5 years ago

A function which will error out if called too soon.

func TestDeferHappensInTheRightOrder(t *testing.T) {
  okay := false
  func f() {
    if !okay {
      t.Error("Deferred function called too soon")
    }
  }
  defer Should(f(), "defer doesn't work the way you might think it should")
  okay = true
  // This test will fail.
}
pboothe commented 5 years ago

Don't forget to update the package name in the go files!