Compare commits

..

4 Commits

Author SHA1 Message Date
a0d52fc093 update data type 2025-05-10 20:39:12 +08:00
93bed37b9c update data type 2025-05-10 20:38:12 +08:00
4eb74a4e3a Merge pull request '升级exception, 简化逻辑' (#1) from feature/upgrade_exception into master
Reviewed-on: #1
2025-05-10 19:37:45 +08:00
1718c9c8ad 优化Error实现 2025-05-10 19:37:27 +08:00
2 changed files with 13 additions and 6 deletions

View File

@ -20,7 +20,7 @@ type IException interface {
// Message 获取错误信息 // Message 获取错误信息
Message() string Message() string
// Data 获取异常时的返回数据 // Data 获取异常时的返回数据
Data() map[string]any Data() any
// ToError 转换为内置error类型 // ToError 转换为内置error类型
ToError() error ToError() error
// IsCode 是否为指定code // IsCode 是否为指定code

View File

@ -8,6 +8,7 @@
package exception package exception
import ( import (
"encoding/json"
"errors" "errors"
"fmt" "fmt"
"runtime" "runtime"
@ -23,12 +24,18 @@ import (
type Exception struct { type Exception struct {
code any code any
message string message string
data map[string]any data any
stack string stack string
} }
func (e *Exception) Error() string { func (e *Exception) Error() string {
return e.Message() mapData := map[string]any{
"code": e.Code(),
"msg": e.Message(),
"data": e.Data(),
}
byteData, _ := json.Marshal(mapData)
return string(byteData)
} }
func (e *Exception) GetStack() string { func (e *Exception) GetStack() string {
@ -43,7 +50,7 @@ func (e *Exception) Message() string {
return e.message return e.message
} }
func (e *Exception) Data() map[string]any { func (e *Exception) Data() any {
return e.data return e.data
} }
@ -86,7 +93,7 @@ func NewWithCodeAndData(code any, data map[string]any) IException {
// Author : go_developer@163.com<白茶清欢> // Author : go_developer@163.com<白茶清欢>
// //
// Date : 21:28 2022/6/25 // Date : 21:28 2022/6/25
func New(code any, data map[string]any, defaultMessage ...string) IException { func New(code any, data any, defaultMessage ...string) IException {
if nil == data { if nil == data {
// 保证数据结构的一致性, 同时避免后续使用出现空指针 // 保证数据结构的一致性, 同时避免后续使用出现空指针
data = map[string]any{} data = map[string]any{}
@ -157,6 +164,6 @@ func IsSuccess(e *Exception) bool {
// Author : go_developer@163.com<白茶清欢> // Author : go_developer@163.com<白茶清欢>
// //
// Date : 22:35 2022/6/25 // Date : 22:35 2022/6/25
func NewSuccess(data map[string]any) IException { func NewSuccess(data any) IException {
return New(defaultSuccessCode, data, "") return New(defaultSuccessCode, data, "")
} }