recoverer.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. }
  15. type Recoverer interface {
  16. Recover(v interface{})
  17. }
  18. // 异常时恢复代码
  19. type PanicRecover struct {
  20. Ctx *context.Context
  21. LogID string
  22. }
  23. type GeneralError struct {
  24. ErrCode int `json:"err_code" description:"服务器具体错误码"`
  25. ErrMsg string `json:"err_msg" description:"服务器错误描述"`
  26. }
  27. func (pr *PanicRecover) Recover(v interface{}) {
  28. generalError := GetGeneralError(v)
  29. if generalError == nil {
  30. generalError = &GeneralError{
  31. ErrCode: ERRCODE_FAIL,
  32. ErrMsg: ERRMSG_UNKNOWN,
  33. }
  34. }
  35. pr.Ctx.Output.JSON(Response{
  36. Code: generalError.ErrCode,
  37. Msg: generalError.ErrMsg,
  38. }, false, false)
  39. }
  40. func GetGeneralError(val interface{}) *GeneralError {
  41. generalError := &GeneralError{}
  42. v := reflect.ValueOf(val)
  43. if v.Kind() == reflect.Ptr {
  44. v = v.Elem()
  45. }
  46. flag := false
  47. if v.Kind() == reflect.Struct {
  48. numField := v.NumField()
  49. for i := 0; i < numField; i++ {
  50. if v.Type().Field(i).Name == "ErrCode" && v.Type().Field(i).Type.Kind() == reflect.Int {
  51. generalError.ErrCode = int(v.Field(i).Int())
  52. flag = true
  53. }
  54. if v.Type().Field(i).Name == "ErrMsg" && v.Type().Field(i).Type.Kind() == reflect.String {
  55. generalError.ErrMsg = v.Field(i).String()
  56. }
  57. }
  58. }
  59. if flag {
  60. return generalError
  61. }
  62. return nil
  63. }