err_handler.go 1.1 KB
package xerr

import (
	"context"
	"github.com/samber/lo"
	"github.com/zeromicro/go-zero/core/logx"
	"net/http"
)

func ErrorHandlerCtx(ctx context.Context, err error) (int, any) {
	//错误返回
	var (
		errCode = ServerCommonError
		errMsg  = ""
	)
	// 自定义错误类型
	if codeError, ok := err.(*CodeError); ok {
		errCode = codeError.GetErrCode()
		errMsg = codeError.GetErrMsg()
	}
	logx.WithContext(ctx).Errorf("【ERROR-HANDLER】 : %+v ", err)
	response := Error(int(errCode), lo.Ternary(errMsg != "", errMsg, MapErrMsg(errCode)))
	response.Error = err.Error()
	return http.StatusOK, response
}

func OkHandlerCtx(ctx context.Context, a any) any {
	return Success(a)
}

func Success(data interface{}) *ResponseSuccessBean {
	return &ResponseSuccessBean{Code: 0, Msg: "OK", Data: data}
}

type ResponseSuccessBean struct {
	Code uint32      `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

type ResponseErrorBean struct {
	Code  int    `json:"code"`
	Msg   string `json:"msg"`
	Error string `json:"err"`
}

func Error(errCode int, errMsg string) *ResponseErrorBean {
	return &ResponseErrorBean{Code: errCode, Msg: errMsg}
}