You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
62 lines
1.3 KiB
Go
62 lines
1.3 KiB
Go
3 years ago
|
package response
|
||
|
|
||
|
import (
|
||
|
"github.com/pkg/errors"
|
||
|
"github.com/zeromicro/go-zero/core/logx"
|
||
|
"github.com/zeromicro/go-zero/rest/httpx"
|
||
|
"google.golang.org/grpc/status"
|
||
|
"live-service/common/nerr"
|
||
|
"net/http"
|
||
|
)
|
||
|
|
||
|
type Body struct {
|
||
|
Code uint32 `json:"code"`
|
||
|
Msg string `json:"message"`
|
||
|
Data interface{} `json:"data,omitempty"`
|
||
|
}
|
||
|
|
||
|
func Error(code uint32, msg string) *Body {
|
||
|
return &Body{
|
||
|
Code: code,
|
||
|
Msg: msg,
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func Success(data interface{}) *Body {
|
||
|
return &Body{
|
||
|
Code: http.StatusOK,
|
||
|
Msg: "成功",
|
||
|
Data: data,
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func Response(req *http.Request, w http.ResponseWriter, resp interface{}, err error) {
|
||
|
if err == nil {
|
||
|
r := Success(resp)
|
||
|
httpx.WriteJson(w, http.StatusOK, r)
|
||
|
return
|
||
|
}
|
||
|
// 错误返回
|
||
|
errCode := nerr.ServerCommonError
|
||
|
errMsg := nerr.MapErrMsg(errCode)
|
||
|
|
||
|
cause := errors.Cause(err)
|
||
|
if e, ok := cause.(*nerr.Error); ok {
|
||
|
// 自定义错误类型
|
||
|
errCode = e.Code
|
||
|
errMsg = e.Msg
|
||
|
} else {
|
||
|
// grpc err
|
||
|
if gStatus, ok := status.FromError(cause); ok {
|
||
|
grpcCode := uint32(gStatus.Code())
|
||
|
if nerr.IsCodeErr(grpcCode) {
|
||
|
// 区分自定义错误 系统底层、DB错误 (底层、DB错误不返回前端)
|
||
|
errCode = grpcCode
|
||
|
errMsg = gStatus.Message()
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
logx.WithContext(req.Context()).Errorf("[API-ERROR] %+v", err)
|
||
|
httpx.WriteJson(w, http.StatusBadRequest, Error(errCode, errMsg))
|
||
|
}
|