Skip to content

Latest commit

 

History

History
68 lines (65 loc) · 1.79 KB

README.md

File metadata and controls

68 lines (65 loc) · 1.79 KB

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()
    ...
  })
}