golang: 返回錯誤時列印堆疊

刘宏缔的架构森林發表於2024-12-07

一,預設的錯誤列印:

1,定義函式:

//列印錯誤的堆疊資訊
func PrintStackTrace(err error) {
	// 建立一個緩衝區用於儲存堆疊資訊
	buf := bytes.NewBuffer(nil)

	// 獲取當前goroutine的堆疊資訊
	for i := 0; ; i++ {
		pc, file, line, ok := runtime.Caller(i)
		if !ok {
			break
		}
		fmt.Fprintf(buf, "%d: %s:%d (0x%x)\n", i, file, line, pc)
	}

	// 列印堆疊資訊
	fmt.Println(buf.String())
}

2,呼叫定義的方法

	fields := []string{"id", "addtime","abcd"}

	var rows *sql.Rows
	var err error
	rows,err = config.DBLink.Select(fields).Table(model.PlModel{}.TableName()).Where("uid=? and status=1",uid).Order("id desc").Offset(offset).Limit(size).Rows()

	if err != nil {
		fmt.Println("錯誤資訊:",err)
		fmt.Println("堆疊:")
		config.PrintStackTrace(err)
	}

二,測試效果:


錯誤資訊: Error 1054 (42S22): Unknown column 'abcd' in 'field list'
堆疊:
0: /data/test/config/globalFunction.go:101 (0x9aecd9)
1: /data/test/service/PlService.go:41 (0x9df044)
2: /data/test/controller/userController.go:362 (0xa569f4)
3: /data/gopath/pkg/mod/github.com/gofiber/fiber/v2@v2.52.5/router.go:145 (0x9a639d)
4: /data/gopath/pkg/mod/github.com/gofiber/fiber/v2@v2.52.5/ctx.go:1034 (0x99002c)
5: /data/gopath/pkg/mod/github.com/gofiber/fiber/v2@v2.52.5/router.go:425 (0x9a7fd0)
6: /data/gopath/pkg/mod/github.com/gofiber/fiber/v2@v2.52.5/ctx.go:1031 (0x99001c)
7: /data/gopath/pkg/mod/github.com/gofiber/fiber/v2@v2.52.5/middleware/recover/recover.go:43 (0xa5a0fa)
8: /data/gopath/pkg/mod/github.com/gofiber/fiber/v2@v2.52.5/router.go:145 (0x9a639d)
9: /data/gopath/pkg/mod/github.com/gofiber/fiber/v2@v2.52.5/router.go:172 (0x9a65c8)
10: /data/gopath/pkg/mod/github.com/valyala/fasthttp@v1.57.0/server.go:2385 (0x960dd0)
11: /data/gopath/pkg/mod/github.com/valyala/fasthttp@v1.57.0/workerpool.go:225 (0x96c9f1)
12: /data/gopath/pkg/mod/github.com/valyala/fasthttp@v1.57.0/workerpool.go:197 (0x96c791)
13: /usr/local/soft/go/src/runtime/asm_amd64.s:1700 (0x478160)

相關文章