github.com/duomi520/utils@v0.0.0-20240430123446-e03a4cddd6ec/errors_test.go (about) 1 package utils 2 3 import ( 4 "errors" 5 "fmt" 6 "log/slog" 7 "os" 8 "testing" 9 ) 10 11 func TestStack(t *testing.T) { 12 err1 := errors.New("a error") 13 err2 := WrapStack(1, err1) 14 fmt.Println(err2) 15 fmt.Println(ErrorWithStack(err2)) 16 //wrap 17 err3 := fmt.Errorf("warp %w", err2) 18 fmt.Println(err3) 19 //unwarp 20 err4 := errors.Unwrap(err3) 21 fmt.Println(ErrorWithStack(err4)) 22 //nil 23 fmt.Println(ErrorWithStack(nil)) 24 err5 := WrapStack(1, nil) 25 fmt.Println(err5) 26 } 27 28 /* 29 a error 30 [errors_test.go:13] a error 31 warp a error 32 [errors_test.go:13] a error 33 34 <nil> 35 */ 36 37 func TestReplaceAttr(t *testing.T) { 38 err1 := errors.New("something") 39 err2 := WrapStack(1, err1) 40 err3 := fmt.Errorf("warp1 %w", err2) 41 err4 := WrapStack(1, err3) 42 err5 := fmt.Errorf("warp2 %w", err4) 43 err6 := fmt.Errorf("warp3 %w", err5) 44 err7 := WrapStack(1, err6) 45 h := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ 46 ReplaceAttr: ReplaceAttr, 47 }) 48 fmt.Println(ErrorWithFullStack(err7)) 49 logger := slog.New(h) 50 logger.Error("message", err7) 51 } 52 53 /* 54 [errors_test.go:44] warp3 warp2 warp1 something 55 warp2 warp1 something 56 [errors_test.go:41] warp1 something 57 [errors_test.go:39] somethin 58 time=2024-04-30T00:00:12.360+08:00 level=ERROR msg=message trace="[errors_test.go:44] warp3 warp2 warp1 something\nwarp2 warp1 something\n[errors_test.go:41] warp1 something\n[errors_test.go:39] somethin" 59 */