package middleware

import (
	. "bp.jydev.jianyu360.cn/BaseService/gateway/common/gatecode"
	"bp.jydev.jianyu360.cn/BaseService/gateway/core/logs"
	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/net/gtrace"
)

// ErrorHandler 统一异常拦截、提醒，及日志打印中间件
func ErrorHandler(r *ghttp.Request) {
	r.Middleware.Next()
	_, span := gtrace.NewSpan(r.Context(), "ErrorHandler")
	defer span.End()
	// 程序异常信息处理
	err := r.GetError()
	if err != nil {
		gCode := gerror.Code(err)
		if gCode == gcode.CodeNil { // 非定义异常
			gCode = gcode.New(int(OTHER_ERR_UNDEFINED), OTHER_ERR_UNDEFINED.String(), err.Error())
			err = gerror.NewCode(gCode, "非定义异常")
		}
		//	返回固定的友好信息
		r.Response.ClearBuffer()
		r.Response.WriteJson(map[string]interface{}{
			"error_code": gCode.Code(),
			"error_msg":  gCode.Message(),
		})
	}
	// 记录到日志文件并通知
	go logs.GateWayServerLog.RecordLogAndNotice(r, err)
}
