github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/zerror/catch_test.go (about)

     1  package zerror_test
     2  
     3  import (
     4  	"errors"
     5  	"strconv"
     6  	"testing"
     7  
     8  	"github.com/sohaha/zlsgo"
     9  	"github.com/sohaha/zlsgo/zerror"
    10  )
    11  
    12  func TestTryCatch(t *testing.T) {
    13  	tt := zlsgo.NewTest(t)
    14  	err := zerror.TryCatch(func() error {
    15  		zerror.Panic(zerror.New(500, "测试"))
    16  		return nil
    17  	})
    18  	tt.EqualTrue(err != nil)
    19  	tt.Equal("测试", err.Error())
    20  	t.Logf("%+v", err)
    21  	code, _ := zerror.UnwrapCode(err)
    22  	tt.Equal(zerror.ErrCode(500), code)
    23  
    24  	err = zerror.TryCatch(func() error {
    25  		panic("测试")
    26  		return nil
    27  	})
    28  	tt.Equal("测试", err.Error())
    29  	t.Logf("%+v", err)
    30  }
    31  
    32  func BenchmarkTryCatch_normal(b *testing.B) {
    33  	for i := 0; i < b.N; i++ {
    34  		_ = zerror.TryCatch(func() error {
    35  			e := strconv.Itoa(i)
    36  			_ = e
    37  			return nil
    38  		})
    39  	}
    40  }
    41  
    42  func BenchmarkTryCatch_panic(b *testing.B) {
    43  	for i := 0; i < b.N; i++ {
    44  		_ = zerror.TryCatch(func() error {
    45  			e := strconv.Itoa(i)
    46  			panic(e)
    47  		})
    48  	}
    49  }
    50  
    51  func BenchmarkTryCatch_error(b *testing.B) {
    52  	for i := 0; i < b.N; i++ {
    53  		_ = zerror.TryCatch(func() error {
    54  			e := strconv.Itoa(i)
    55  			return errors.New(e)
    56  		})
    57  	}
    58  }