103 lines
2.7 KiB
Go
103 lines
2.7 KiB
Go
package utils
|
|
|
|
import (
|
|
"github.com/flipped-aurora/gin-vue-admin/server/plugin/wechat-integration/model/response"
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// ResponseHelper 响应助手
|
|
type ResponseHelper struct{}
|
|
|
|
// Success 成功响应
|
|
func (r *ResponseHelper) Success(c *gin.Context, data interface{}) {
|
|
c.JSON(200, response.SuccessResponse(data))
|
|
}
|
|
|
|
// SuccessWithMsg 带消息的成功响应
|
|
func (r *ResponseHelper) SuccessWithMsg(c *gin.Context, data interface{}, msg string) {
|
|
c.JSON(200, response.SuccessResponseWithMsg(data, msg))
|
|
}
|
|
|
|
// Error 错误响应
|
|
func (r *ResponseHelper) Error(c *gin.Context, code int) {
|
|
c.JSON(200, response.ErrorResponse(code))
|
|
}
|
|
|
|
// ErrorWithMsg 带消息的错误响应
|
|
func (r *ResponseHelper) ErrorWithMsg(c *gin.Context, code int, msg string) {
|
|
c.JSON(200, response.ErrorResponseWithMsg(code, msg))
|
|
}
|
|
|
|
// HandleError 处理错误并返回相应的错误码
|
|
func (r *ResponseHelper) HandleError(c *gin.Context, err error) {
|
|
if err == nil {
|
|
return
|
|
}
|
|
|
|
errMsg := err.Error()
|
|
|
|
// 根据错误信息返回相应的错误码
|
|
switch errMsg {
|
|
case "用户不存在":
|
|
r.Error(c, response.ERROR_USER_NOT_FOUND)
|
|
case "获取用户 OpenID 失败":
|
|
r.Error(c, response.ERROR_WX_OPENID_EMPTY)
|
|
case "微信小程序 Code2Session 失败":
|
|
r.Error(c, response.ERROR_WX_SESSION_FAILED)
|
|
case "解密手机号失败":
|
|
r.Error(c, response.ERROR_WX_PHONE_DECRYPT_FAILED)
|
|
case "解密数据中未找到手机号":
|
|
r.Error(c, response.ERROR_WX_PHONE_NOT_FOUND)
|
|
case "用户 SessionKey 不存在,请重新登录":
|
|
r.Error(c, response.ERROR_WX_SESSIONKEY_EMPTY)
|
|
default:
|
|
// 检查是否是数据库相关错误
|
|
if isDBError(errMsg) {
|
|
r.ErrorWithMsg(c, response.ERROR_INTERNAL, "数据库操作失败")
|
|
} else {
|
|
r.ErrorWithMsg(c, response.ERROR_COMMON, errMsg)
|
|
}
|
|
}
|
|
}
|
|
|
|
// isDBError 判断是否是数据库错误
|
|
func isDBError(errMsg string) bool {
|
|
dbErrorKeywords := []string{
|
|
"Unknown column",
|
|
"Table doesn't exist",
|
|
"Duplicate entry",
|
|
"Data too long",
|
|
"cannot be null",
|
|
"foreign key constraint",
|
|
}
|
|
|
|
for _, keyword := range dbErrorKeywords {
|
|
if contains(errMsg, keyword) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// contains 检查字符串是否包含子字符串
|
|
func contains(s, substr string) bool {
|
|
return len(s) >= len(substr) && (s == substr ||
|
|
(len(s) > len(substr) &&
|
|
(s[:len(substr)] == substr ||
|
|
s[len(s)-len(substr):] == substr ||
|
|
indexOf(s, substr) >= 0)))
|
|
}
|
|
|
|
// indexOf 查找子字符串的位置
|
|
func indexOf(s, substr string) int {
|
|
for i := 0; i <= len(s)-len(substr); i++ {
|
|
if s[i:i+len(substr)] == substr {
|
|
return i
|
|
}
|
|
}
|
|
return -1
|
|
}
|
|
|
|
// 全局响应助手实例
|
|
var ResponseUtil = &ResponseHelper{}
|