|
|
|
|
package nstatus
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"fmt"
|
|
|
|
|
"git.noahlan.cn/noahlan/ntool-biz/core/nstatus/code"
|
|
|
|
|
"git.noahlan.cn/noahlan/ntool/njson"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type ResultType string
|
|
|
|
|
|
|
|
|
|
const (
|
|
|
|
|
CommonResult ResultType = "common" // 一般返回值
|
|
|
|
|
ApiErr = "api_err" // ApiErr Api错误,用于返回携带http状态码的错误返回信息
|
|
|
|
|
BizErr = "biz_err" // BizErr 业务错误,错误状态码统一为500,详细状态码在返回体的code中
|
|
|
|
|
RpcErr = "rpc_err" // RpcErr Rpc错误
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// Result 统一返回结果 结构体
|
|
|
|
|
// {"code":200,"msg":"OK","data":{}}
|
|
|
|
|
// API RPC 共用
|
|
|
|
|
type Result struct {
|
|
|
|
|
Code int `json:"code"` // 返回编码(业务+错误)
|
|
|
|
|
Msg string `json:"msg"` // 消息
|
|
|
|
|
Data any `json:"data,omitempty,optional"` // 数据
|
|
|
|
|
Type ResultType `json:"-,omitempty,optional"` // Typ 返回结果类型,忽略json
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func NewResult(code int, message string, typ ResultType) *Result {
|
|
|
|
|
return NewResultWithData(code, message, typ, nil)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func NewResultWithData(code int, message string, typ ResultType, data any) *Result {
|
|
|
|
|
return &Result{
|
|
|
|
|
Code: code,
|
|
|
|
|
Msg: message,
|
|
|
|
|
Data: data,
|
|
|
|
|
Type: typ,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Error 错误输出,同时可作为错误
|
|
|
|
|
func (r *Result) Error() string {
|
|
|
|
|
return r.Msg
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (r *Result) Err() error {
|
|
|
|
|
return r
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (r *Result) Cause() error {
|
|
|
|
|
return r
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (r *Result) String() string {
|
|
|
|
|
return fmt.Sprintf("Code:%d Message:%s Data:%v", r.Code, r.Msg, r.Data)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// JsonString 返回JsonString格式
|
|
|
|
|
func (r *Result) JsonString() string {
|
|
|
|
|
return njson.MarshalStrSafe(r)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// FromError returns a Status representation of err.
|
|
|
|
|
//
|
|
|
|
|
// - If err was produced by this package *Result`, the appropriate Result is returned.
|
|
|
|
|
// - If err is nil, a nil is returned.
|
|
|
|
|
//
|
|
|
|
|
// - Otherwise, err is an error not compatible with this package. In this
|
|
|
|
|
// case, a *Result is returned with code.StatusUnknown and err's Error() message,
|
|
|
|
|
// and ok is false.
|
|
|
|
|
func FromError(err error) (*Result, bool) {
|
|
|
|
|
if err == nil {
|
|
|
|
|
return nil, false
|
|
|
|
|
}
|
|
|
|
|
if se, ok := err.(*Result); ok {
|
|
|
|
|
return se, true
|
|
|
|
|
}
|
|
|
|
|
return NewResult(code.StatusUnknown, err.Error(), CommonResult), false
|
|
|
|
|
}
|