Skip to content

Latest commit

 

History

History
79 lines (73 loc) · 2.15 KB

File metadata and controls

79 lines (73 loc) · 2.15 KB

GoDoc Build Status Coverage Status

exception

exception handling for golang

usage

basics

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

multiple errors

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

unknown errors

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

panic

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

ignore

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

finally

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