Skip to content
/ catch Public

Catch provides controlled recovery of panics using a predefined error with a cause.

License

Notifications You must be signed in to change notification settings

tada/catch

Repository files navigation

Catch provides controlled recovery of panics using a special error implementation that has a cause (another error).

How to get:

go get github.com/tada/catch

Sample usage

Consider the following code where more than half of the lines are devoted to error handling:

func foo() (error, int) {
  a, err := x()
  if err != nil {
     return err
  }
  b, err := y()
  if err != nil {
     return err
  }
  c, err := z()
  if err != nil {
     return err
  }
  return a + b * c
}

using catch on all involved functions, the code can instead very distinct:

func foo() int {
  return x() + y() * z()
}

Leaf functions such as x, y, and z, where errors are produced may look something like this without catch:

func x() (error, int) {
  err, v := computeSomeValue()
  if err != nil {
  	return 0, err
  }
  return int(v)
}

and like this with catch:

func x() int {
  err, v := computeSomeValue()
  if err != nil {
    panic(catch.Error(err))
  }
  return int(v)
}

At the very top, errors produced somewhere in the executed code can be recovered using the catch.Do function which will recover only catch.Error and return its cause:

func furtherUp() error {
  return catch.Do(func() {
    x := foo()
    ...
  })
}

About

Catch provides controlled recovery of panics using a predefined error with a cause.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages