The try...catch statement alternative in Golang.
go get -u github.com/ghosind/go-try
There is the simplest example to run a function and handle the error in the catch function that the try function returned.
out, err := try.TryCatch(func () (error) {
// Do something
return err
}, func (err error) {
// The function will not executing if err is nil.
// Handle error...
})The try functions will return two values. The first value is the all values the try function returned, and the second value is the error that the try function returns or it panics.
out, err := try.Try(func () (string, error) {
return "Hello world", errors.New("expected error")
})
fmt.Println(out)
fmt.Println(err)
// [Hello world, expected error]
// expected errorThe package provides four forms for the try statement alternative:
TryTryFinallyTryCatchTryCatchFinally
In default cases, the try functions will catch the error that the try function panics, and you can set the CatchPanic variable to false to disable it.
try.CatchPanic = false
try.Try(func () {
panic("panic error")
})
// panic: expected error