gotry/README.md
2021-10-01 18:46:01 +02:00

963 B

gotry

This package is a fork of lainio's err2 package with an improved code generator.

Add custom try package to your project

go install code.thetadev.de/ThetaDev/gotry/gotry_generate

gotry_generate -init

Add type definitions

📂 try/types.csv

<Handler method name>;<Type>;<Import#1>;<Import#2>;...

# Example:
DB;*gorm.DB;gorm.io/gorm

# Add +s to the method name to generate 2 handlers for single values and slices
String+s;string

Generate

go generate ./try

Handle errors

Instead of the idiomatic go way of handling errors, which involves if-conditions for every possible error, ...

func myFunction() (err error) {
  b, err := ioutil.ReadAll(r)
  if err != nil {
    return err
  }
}

you can wrap the error-throwing function in a try wrapper.

func myFunction() (err error) {
  defer err2.Return(&err)

  b := try.Bytes(ioutil.ReadAll(r))

  return
}