GoCollections/exceptions/Exception.go

40 lines
693 B
Go
Raw Normal View History

2021-05-20 17:32:35 +08:00
package exceptions
2021-05-21 09:41:58 +08:00
import (
"fmt"
"io"
)
2021-05-20 17:32:35 +08:00
type Exception interface {
Error() string
StackTrace() []StackTrace
PrintStackTrace()
PrintStackTraceTo(writer io.Writer)
}
2021-05-21 09:41:58 +08:00
func PrintStackTrace(writer io.Writer, e Exception, exceptionMsg string) {
_, err := fmt.Fprintln(writer, exceptionMsg, e.Error())
if err != nil {
return
}
if e.StackTrace() == nil {
return
}
for _, stackTrace := range e.StackTrace() {
stackTrace.PrintLn(writer)
}
}
func Try(f func() (interface{}, error), catch func(interface{}) interface{}) (ret interface{}) {
defer func() {
if r := recover(); r != nil {
ret = catch(r)
}
}()
ret, err := f()
if err != nil {
ret = catch(err)
}
return
}