exception handling for golang
Basically Try/Catch are just some function wrappers that recover from panics.
exception.Try(func(){
// something that might go wrong
exception.Throw(fmt.Errorf("Some error"))
}).Catch(func(e error){
log.Warningf("An error occured: %s", e)
}).Go()The handler function is chosen by the function signature, that takes the the given object as first and only argument.
type Exception struct{
Message string
}
exception.Try(func(){
// something that might go wrong
exception.Throw(Exception{Message:"This is an exception"})
}).Catch(func(e Exception){
log.Warningf("An exception occured: %s", e.Message)
}).Catch(func(e error){
log.Warningf("An error occured: %s", e)
}).Go()If you call into other people's code and don't know what they might throw in a future version of their code, you can catch that with a catchall function.
exception.Try(func(){
// something that might go wrong
exception.Throw(fmt.Errorf("Some error"))
}).CatchAll(func(e interface{}){
log.Warningf("An error occured: %+v", e)
}).Go()Sometimes you have some code that calls panic.
exception.Try(func(){
// something that might go wrong
panic(fmt.Errorf("Some error"))
}).CatchAll(func(e interface{}){
log.Warningf("An error occured: %+v", e)
}).Go()You just want to try over and over?
stop := false
for !stop {
exception.Try(func(){
// something that might go wrong
panic(fmt.Errorf("Some error"))
stop = true
}).Ignore().Go()
}If you need to run some cleanup code anyways
exception.Try(func(){
// something that might go wrong
panic(fmt.Errorf("Some error"))
}).Ignore().Finally(func(){
// some cleanup
})