github.com/Axway/agent-sdk@v1.1.101/pkg/util/exception/exception.go (about) 1 package exception 2 3 import ( 4 "fmt" 5 "runtime/debug" 6 "strings" 7 ) 8 9 // Block - defines the try, catch and finally code blocks 10 type Block struct { 11 Try func() 12 Catch func(error) 13 Finally func() 14 } 15 16 // Throw - raises the error 17 // Raises the panic error 18 func Throw(err error) { 19 panic(err) 20 } 21 22 // Do - Executes the Exception block. 23 // 1. Defers the finally method, so that it can be called last 24 // 2. Defers the execution of catch, to recover from panic raised by Throw and callback Catch method 25 // 3. Executes the try method, that may raise error by calling Throw method 26 func (block Block) Do() { 27 if block.Try == nil { 28 return 29 } 30 31 if block.Finally != nil { 32 defer block.Finally() 33 } 34 35 if block.Catch != nil { 36 defer func() { 37 if obj := recover(); obj != nil { 38 err := obj.(error) 39 if strings.Contains(err.Error(), "nil pointer dereference") { 40 block.Catch(fmt.Errorf(err.Error() + ": \n " + string(debug.Stack()))) 41 } else { 42 block.Catch(err) 43 } 44 } 45 }() 46 } 47 block.Try() 48 }