task.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package task
  2. import (
  3. "encoding/json"
  4. "time"
  5. "gd_management_gateway/common.in/jsonrpc2"
  6. "gd_management_gateway/common.in/span"
  7. "github.com/astaxie/beego/context"
  8. )
  9. type Task func() error
  10. func Do(er Recoverer, ctx *context.Context, tasks ...Task) {
  11. // task执行返回的error
  12. var taskErr error
  13. // 植入跟踪日志id信息
  14. spanID := span.NewRootSpanID()
  15. ctx.Input.Context.Request.Header.Add("span", spanID.String())
  16. // 开始时间
  17. startTime := uint64(time.Now().UnixNano())
  18. // 抓异常代码
  19. defer func() {
  20. status := "SUCCESS"
  21. // 捕获到panic
  22. if r := recover(); r != nil {
  23. er.Recover(r)
  24. status = "FAIL"
  25. }
  26. // task返回失败
  27. if taskErr != nil {
  28. e := &jsonrpc2.Error{}
  29. if err := json.Unmarshal([]byte(taskErr.Error()), e); err != nil {
  30. ctx.Output.JSON(Response{Code: 10001, Msg: "系统错误"}, false, false)
  31. } else {
  32. ctx.Output.JSON(Response{Code: e.Code, Msg: e.Message}, false, false)
  33. }
  34. status = "FAIL"
  35. }
  36. printAccessLog(ctx, startTime, status, spanID)
  37. }()
  38. for _, task := range tasks {
  39. if task != nil {
  40. if err := task(); err != nil {
  41. taskErr = err
  42. return
  43. }
  44. }
  45. }
  46. }