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.
ntool-biz/core/nstatus/result.go

80 lines
2.2 KiB
Go

1 year ago
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错误
1 year ago
)
// 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
1 year ago
}
func NewResult(code int, message string, typ ResultType) *Result {
return NewResultWithData(code, message, typ, nil)
1 year ago
}
func NewResultWithData(code int, message string, typ ResultType, data any) *Result {
return &Result{
Code: code,
Msg: message,
Data: data,
Type: typ,
}
1 year ago
}
// Error 错误输出,同时可作为错误
func (r *Result) Error() string {
return r.Msg
}
func (r *Result) Err() error {
return r
}
func (r *Result) Cause() error {
return r
1 year ago
}
func (r *Result) String() string {
return fmt.Sprintf("Code:%d Message:%s Data:%v", r.Code, r.Msg, r.Data)
1 year ago
}
// 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
1 year ago
}