65 lines
1.8 KiB
Go
Raw Normal View History

package main
import (
"encoding/json"
"fmt"
//
"github.com/infraboard/mcube/v2/exception"
)
func main() {
err := ValidateToken("")
if err != nil {
fmt.Println(err)
bj, _ := json.Marshal(err)
fmt.Println(string(bj))
// {"service":"","http_code":500,"code":10001,"reason":"","message":"token is empty","meta":{},"data":{}}
if exception.IsApiException(err, 10001) {
fmt.Println("IsApiException: token is empty")
}
}
}
func ValidateToken(token string) error {
if token == "" {
return exception.NewApiException(10001, "token is empty")
}
return nil
}
// func NewApiException(code int, message string) *ApiException {
// return &ApiException{
// HttpCode: 500,
// Code: code,
// Message: message,
// Meta: map[string]any{},
// Data: map[string]any{},
// }
// }
// // ApiException API异常结构体
// // 自定义异常数据结构体, 方便后续的异常处理和日志记录
// type ApiException struct {
// Service string `json:"service"` // 服务名称, 你后端服务多个
// HttpCode int `json:"http_code,omitempty"` // HTTP状态码, 需不需定义明确的http code, 默认500,非2xx
// Code int `json:"code"` // 业务异常码, 具体业务自己定义
// Reason string `json:"reason"` // 异常原因
// Message string `json:"message"` // 详细描述
// Meta map[string]any `json:"meta"` // 元数据
// Data any `json:"data"` // 附加数据
// }
// func (e *ApiException) Error() string {
// return e.Message
// }
// // 辅助函数: IsApiException 判断是否是ApiException
// func IsApiException(err error, code int) bool {
// if v, ok := err.(*ApiException); ok {
// return v.Code == code
// }
// return false
// }