package route

import (
	"github.com/gofiber/fiber/v2"
	"matrix-common/pkg/logger"
	"matrix-middle-service/pkg/resp/errorx"
)

func GlobalErrorHandler() fiber.ErrorHandler {
	return func(ctx *fiber.Ctx, err error) error {
		code := fiber.StatusInternalServerError

		if e, ok := err.(*fiber.Error); ok {
			logger.Log().Debugf("err %v", e)
			code = e.Code
			if code == fiber.StatusNotFound {
				return ctx.Status(fiber.StatusNotFound).JSON(errorx.NewErrorWithCode(code, "页面不存在"))
			}
		}

		err = ctx.Status(code).JSON(errorx.NewDefaultError(err.Error()))
		logger.Log().Errorf("%#v", err)
		if err != nil {
			return ctx.Status(fiber.StatusInternalServerError).SendString("Internal Server Error")
		}

		return nil
	}
}
