Compare commits

...

4 Commits

Author SHA1 Message Date
255d79affb merge master && fix both modify 2025-05-10 19:35:05 +08:00
ca151fbc1f 优化请求成功默认返回文案 2025-02-07 17:17:24 +08:00
907c206627 默认成功状态码增加默认值 2025-02-07 17:13:53 +08:00
1e7f84ed84 支持打印堆栈 2024-09-30 16:13:43 +08:00
3 changed files with 30 additions and 1 deletions

View File

@ -25,4 +25,6 @@ type IException interface {
ToError() error
// IsCode 是否为指定code
IsCode(code any) bool
// GetStack 获取调用堆栈
GetStack() string
}

View File

@ -82,7 +82,7 @@ var (
// messageWithCode 自动在message文案后追加状态码
messageWithCode = true
// defaultSuccessCode 默认代表成功的状态码
defaultSuccessCode any
defaultSuccessCode any = 0
// defaultLanguage 默认的语言
defaultLanguage = "zh"
)

View File

@ -10,6 +10,9 @@ package exception
import (
"errors"
"fmt"
"runtime"
"strconv"
"strings"
)
// Exception 异常接口的具体实现
@ -21,12 +24,17 @@ type Exception struct {
code any
message string
data map[string]any
stack string
}
func (e *Exception) Error() string {
return e.Message()
}
func (e *Exception) GetStack() string {
return e.stack
}
func (e *Exception) Code() any {
return e.code
}
@ -83,10 +91,29 @@ func New(code any, data map[string]any, defaultMessage ...string) IException {
// 保证数据结构的一致性, 同时避免后续使用出现空指针
data = map[string]any{}
}
pcs := make([]uintptr, 128)
n := runtime.Callers(2, pcs)
frames := runtime.CallersFrames(pcs[:n])
var sb strings.Builder
for {
frame, more := frames.Next()
sb.WriteString(frame.Function)
sb.WriteByte('\n')
sb.WriteByte('\t')
sb.WriteString(frame.File)
sb.WriteByte(':')
sb.WriteString(strconv.Itoa(frame.Line))
sb.WriteByte('\n')
if !more {
break
}
}
return &Exception{
code: code,
message: GetMessage(code, defaultMessage...),
data: data,
stack: sb.String(),
}
}