http_result.go 1.7 KB
package result

import (
	"fmt"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-discuss/pkg/xerr"
	"net/http"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/httpx"
	"google.golang.org/grpc/status"
)

// HttpResult http响应结果返回
func HttpResult(r *http.Request, w http.ResponseWriter, resp interface{}, err error) {
	// 成功返回
	if err == nil {
		r := Success(resp)
		httpx.WriteJson(w, http.StatusOK, r)
		return
	}

	//错误返回
	errCode := xerr.ServerCommonError
	errMsg := "服务器开小差啦,稍后再来试一试"
	internalErr := ""
	causeErr := errors.Cause(err)

	codeError := &xerr.CodeError{}
	if ok := errors.As(causeErr, codeError); ok { // 自定义错误类型
		errCode = codeError.GetErrCode()
		errMsg = codeError.GetErrMsg()
		if codeError.InternalError != nil {
			internalErr = codeError.InternalError.Error()
		}
	} else {
		if grpcStatus, ok := status.FromError(causeErr); ok { // grpc err错误
			grpcCode := uint32(grpcStatus.Code())
			if xerr.IsCodeErr(grpcCode) {
				errCode = grpcCode
				errMsg = grpcStatus.Message()
			}
		}
	}
	// TODO:区分自定义错误跟系统底层、db等错误,底层、db错误不能返回给前端
	logx.WithContext(r.Context()).Errorf("【API-ERR】 : %+v ", err)
	response := Error(errCode, errMsg)
	response.Error = internalErr
	httpx.WriteJson(w, http.StatusOK, response)

}

// ParamErrorResult http参数错误返回
func ParamErrorResult(r *http.Request, w http.ResponseWriter, err error) {
	errMsg := fmt.Sprintf("%s ,%s", xerr.MapErrMsg(xerr.RequestParamError), err.Error())
	httpx.WriteJson(w, http.StatusBadRequest, Error(xerr.RequestParamError, errMsg))
}