recoverer.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package task
  2. import (
  3. "reflect"
  4. "github.com/astaxie/beego/context"
  5. )
  6. const (
  7. HTTPCODE_500 = 500
  8. ERRCODE_FAIL = 10001
  9. ERRMSG_UNKNOWN = "系统错误"
  10. )
  11. type Response struct {
  12. Code int `json:"code" description:"返回码"`
  13. Msg string `json:"msg" description:"错误消息" default:""`
  14. OrderNo string `json:"order_no,omitempty"`
  15. }
  16. type Recoverer interface {
  17. Recover(v interface{})
  18. }
  19. // 异常时恢复代码
  20. type PanicRecover struct {
  21. Ctx *context.Context
  22. LogID string
  23. }
  24. type GeneralError struct {
  25. ErrCode int `json:"err_code" description:"服务器具体错误码"`
  26. ErrMsg string `json:"err_msg" description:"服务器错误描述"`
  27. }
  28. func (pr *PanicRecover) Recover(v interface{}) {
  29. generalError := GetGeneralError(v)
  30. if generalError == nil {
  31. generalError = &GeneralError{
  32. ErrCode: ERRCODE_FAIL,
  33. ErrMsg: ERRMSG_UNKNOWN,
  34. }
  35. }
  36. pr.Ctx.Output.JSON(Response{
  37. Code: generalError.ErrCode,
  38. Msg: generalError.ErrMsg,
  39. }, false, false)
  40. }
  41. func GetGeneralError(val interface{}) *GeneralError {
  42. generalError := &GeneralError{}
  43. v := reflect.ValueOf(val)
  44. if v.Kind() == reflect.Ptr {
  45. v = v.Elem()
  46. }
  47. flag := false
  48. if v.Kind() == reflect.Struct {
  49. numField := v.NumField()
  50. for i := 0; i < numField; i++ {
  51. if v.Type().Field(i).Name == "ErrCode" && v.Type().Field(i).Type.Kind() == reflect.Int {
  52. generalError.ErrCode = int(v.Field(i).Int())
  53. flag = true
  54. }
  55. if v.Type().Field(i).Name == "ErrMsg" && v.Type().Field(i).Type.Kind() == reflect.String {
  56. generalError.ErrMsg = v.Field(i).String()
  57. }
  58. }
  59. }
  60. if flag {
  61. return generalError
  62. }
  63. return nil
  64. }