gitee.com/quant1x/gox@v1.21.2/runtime/recover.go (about)

     1  package runtime
     2  
     3  import (
     4  	"fmt"
     5  	"gitee.com/quant1x/gox/logger"
     6  	"runtime/debug"
     7  )
     8  
     9  // Deprecated: 废弃 [wangfeng on 2024/2/27 07:52]
    10  func sprintf(v ...any) string {
    11  	n := len(v)
    12  	switch n {
    13  	case 0:
    14  		// 无参数返回长度0的字符串
    15  		return ""
    16  	default:
    17  		// 如果第1个元素是string, 则按照fmt.Sprintf来处理, 否则, 统一fmt.Sprint
    18  		// 这样做的目的为了捕获异常时, 可以允许关注特别信息
    19  		switch tv := v[0].(type) {
    20  		case string:
    21  			return fmt.Sprintf(tv, v[1:]...)
    22  		default:
    23  			return fmt.Sprint(v...)
    24  		}
    25  	}
    26  }
    27  
    28  // 捕获异常, 是否忽略异常
    29  func catchException(err any, ignore bool, format string, a ...any) {
    30  	if err != nil {
    31  		//warning := sprintf(v...)
    32  		warning := fmt.Sprintf(format, a)
    33  		stack := string(debug.Stack())
    34  		loggerFunc := logger.Fatalf
    35  		if ignore {
    36  			loggerFunc = logger.Errorf
    37  		} else {
    38  			fmt.Printf("\nerr=%v, stack=%s\n", err, stack)
    39  		}
    40  		loggerFunc("%s exception: warning=%s, error=%+v, stack=%s", ApplicationName(), warning, err, stack)
    41  	}
    42  }
    43  
    44  // CatchPanic 捕获panic
    45  func CatchPanic(format string, a ...any) {
    46  	err := recover()
    47  	catchException(err, false, format, a...)
    48  }
    49  
    50  // IgnorePanic 通用捕获panic, 忽略异常, 继续执行
    51  func IgnorePanic(format string, a ...any) {
    52  	err := recover()
    53  	catchException(err, true, format, a...)
    54  }
    55  
    56  // IgnorePanicAndNoLog 忽略panic且不记录日志
    57  func IgnorePanicAndNoLog() {
    58  	_ = recover()
    59  }