exception.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package exception
  2. import (
  3. "errors"
  4. "fmt"
  5. "github.com/tal-tech/go-zero/core/logx"
  6. )
  7. type Exception interface {
  8. }
  9. type TryStruct struct {
  10. catches map[string]HandlerEx
  11. try func()
  12. }
  13. func Try(tryHandler func()) *TryStruct {
  14. tryStruct := TryStruct{
  15. catches: make(map[string]HandlerEx),
  16. try: tryHandler,
  17. }
  18. return &tryStruct
  19. }
  20. type HandlerEx func(Exception)
  21. func (sel *TryStruct) Catches(exceptionId string, catch func(Exception)) *TryStruct {
  22. sel.catches[exceptionId] = catch
  23. return sel
  24. }
  25. func (sel *TryStruct) Catch(catch func(Exception)) *TryStruct {
  26. sel.catches["default"] = catch
  27. return sel
  28. }
  29. func (sel *TryStruct) Finally(finally func()) {
  30. defer func() {
  31. if e := recover(); nil != e {
  32. exception := ""
  33. switch e.(type) {
  34. case string:
  35. exception = e.(string)
  36. case error:
  37. err := e.(error)
  38. exception = err.Error()
  39. }
  40. if catch, ok := sel.catches[exception]; ok {
  41. catch(e)
  42. } else if catch, ok = sel.catches["default"]; ok {
  43. catch(e)
  44. }
  45. logx.Info("[Exception] err:", e)
  46. }
  47. finally()
  48. }()
  49. sel.try()
  50. }
  51. func Throw(err interface{}) Exception {
  52. switch err.(type) {
  53. case string:
  54. err = errors.New(err.(string))
  55. case int32:
  56. errStr := fmt.Sprintf("%d", err)
  57. err = errors.New(errStr)
  58. }
  59. panic(err)
  60. }
  61. func MakeError(errCode int32, errStr string) error {
  62. s := fmt.Sprintf("%d@%s", errCode, errStr)
  63. return errors.New(s)
  64. }