瀏覽代碼

优化堆栈显示,修复错误码错误无堆栈信息的bug

jys 2 年之前
父節點
當前提交
64999f21b7
共有 2 個文件被更改,包括 17 次插入3 次删除
  1. 9 3
      v2alpha/errors.go
  2. 8 0
      v2alpha/public.go

+ 9 - 3
v2alpha/errors.go

@@ -41,7 +41,9 @@ func (w *withStack) Format(s fmt.State, verb rune) {
 	switch verb {
 	case 'v':
 		if s.Flag('+') {
-			_, _ = fmt.Fprintf(s, "%+v", w.Cause())
+			if w.Cause() != nil {
+				_, _ = fmt.Fprintf(s, "%+v", w.Cause())
+			}
 			w.stack.Format(s, verb)
 			return
 		}
@@ -66,7 +68,9 @@ func (w *withMessage) Format(s fmt.State, verb rune) {
 	case 'v':
 		if s.Flag('+') {
 			_, _ = io.WriteString(s, w.msg+": ")
-			_, _ = fmt.Fprintf(s, "%+v\n", w.Cause())
+			if w.Cause() != nil {
+				_, _ = fmt.Fprintf(s, "%+v", w.Cause())
+			}
 			return
 		}
 		fallthrough
@@ -90,7 +94,9 @@ func (w *withCode) Format(s fmt.State, verb rune) {
 	case 'v':
 		if s.Flag('+') {
 			_, _ = io.WriteString(s, w.Msg+"\n")
-			_, _ = fmt.Fprintf(s, "%+v\n", w.Cause())
+			if w.Cause() != nil {
+				_, _ = fmt.Fprintf(s, "%+v", w.Cause())
+			}
 			return
 		}
 		fallthrough

+ 8 - 0
v2alpha/public.go

@@ -45,6 +45,14 @@ func WithCode[T codeType](err error, businessCode T, options ...Option) error {
 	for _, option := range options {
 		option(ret)
 	}
+
+	if err == nil {
+		return &withStack{
+			error: ret,
+			stack: callers(),
+		}
+	}
+
 	return ret
 }