package middleware

import (
	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/net/ghttp"
)

func ErrorHandler(r *ghttp.Request) {
	r.Middleware.Next()
	var (
		err  = r.GetError()
		res  = r.GetHandlerResponse()
		code = gerror.Code(err)
	)
	if code == nil {
		code = gcode.CodeNil
	}
	if err != nil && (code == gcode.CodeNil || code == gcode.CodeInternalPanic) {
		r.Response.Status = 200
		r.Response.ClearBuffer()
		r.Response.WriteJson(ghttp.DefaultHandlerResponse{
			Code:    code.Code(),
			Message: code.Message(),
			Data:    res,
		})
	}
}
