recovery_test.go 1004 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package recovery
  2. import (
  3. "context"
  4. "fmt"
  5. "testing"
  6. "github.com/go-kratos/kratos/v2/errors"
  7. )
  8. func TestOnce(t *testing.T) {
  9. defer func() {
  10. if recover() != nil {
  11. t.Error("fail")
  12. }
  13. }()
  14. next := func(context.Context, any) (any, error) {
  15. panic("panic reason")
  16. }
  17. _, e := Recovery(WithHandler(func(ctx context.Context, _, err any) error {
  18. _, ok := ctx.Value(Latency{}).(float64)
  19. if !ok {
  20. t.Errorf("not latency")
  21. }
  22. return errors.InternalServer("RECOVERY", fmt.Sprintf("panic triggered: %v", err))
  23. }))(next)(context.Background(), "panic")
  24. t.Logf("succ and reason is %v", e)
  25. }
  26. func TestNotPanic(t *testing.T) {
  27. next := func(_ context.Context, req any) (any, error) {
  28. return req.(string) + "https://go-kratos.dev", nil
  29. }
  30. _, e := Recovery(WithHandler(func(_ context.Context, _ any, err any) error {
  31. return errors.InternalServer("RECOVERY", fmt.Sprintf("panic triggered: %v", err))
  32. }))(next)(context.Background(), "notPanic")
  33. if e != nil {
  34. t.Errorf("e isn't nil")
  35. }
  36. }