diff --git a/events/events_test.go b/events/events_test.go index c0493c0..594fb46 100644 --- a/events/events_test.go +++ b/events/events_test.go @@ -402,8 +402,25 @@ func Test_EventStructDataFilter(t *testing.T) { args := "index data" res := filter.Trigger(TestEventStructDataFilter{ Data: initData, - }, nil, args) + }, args) check := "init => index data" eq(res, check, "Test_EventStructDataFilter") } + +func Test_FilterPanic(t *testing.T) { + defer func() { + if e := recover(); e == nil { + t.Error("should panic error") + } + }() + + filter := NewFilter() + + // 事件注册 + filter.Listen("panic", func(val string) string { + return val + }, DefaultSort) + + _ = filter.Trigger("panic") +} diff --git a/events/filter.go b/events/filter.go index f50c8b3..5b767d3 100644 --- a/events/filter.go +++ b/events/filter.go @@ -40,13 +40,22 @@ func (this *Filter) Subscribe(subscribers ...any) *Filter { return this } -func (this *Filter) Trigger(event any, value any, params ...any) any { +func (this *Filter) Trigger(event any, params ...any) any { this.mu.RLock() defer this.mu.RUnlock() + var value any + eventName := formatName(event) if this.pool.IsStruct(event) { value = event + } else { + if len(params) == 0 { + panic("go-events: Filter trigger func need value") + } + + value = params[0] + params = params[1:] } listeners := this.listener[eventName] diff --git a/events/helper.go b/events/helper.go index 72624fb..55e92c8 100644 --- a/events/helper.go +++ b/events/helper.go @@ -26,8 +26,8 @@ func AddFilter(event any, listener any, sort int) { } // 触发过滤器 -func ApplyFilters(event any, value any, params ...any) any { - return Default.Filter().Trigger(event, value, params...) +func ApplyFilters(event any, params ...any) any { + return Default.Filter().Trigger(event, params...) } // 移除过滤器 diff --git a/events/pool.go b/events/pool.go index 70e511c..dc04541 100644 --- a/events/pool.go +++ b/events/pool.go @@ -21,7 +21,7 @@ func NewPool() *Pool { func (this *Pool) CallFunc(fn any, args []any) any { fnObject := reflect.ValueOf(fn) if !(fnObject.IsValid() && fnObject.Kind() == reflect.Func) { - panic("pool: func type error") + panic("go-events: call func type error") } return this.Call(fnObject, args) @@ -32,12 +32,12 @@ func (this *Pool) CallStructMethod(in any, method string, args []any) any { typ := reflect.TypeOf(in) if typ.Kind() != reflect.Pointer && typ.Kind() != reflect.Struct { - panic("pool: struct type error") + panic("go-events: call struct type error") } newMethod, ok := typ.MethodByName(method) if !ok { - panic("pool: method not exists") + panic("go-events: call method not exists") } args = append([]any{in}, args...) @@ -50,7 +50,7 @@ func (this *Pool) Call(fn reflect.Value, args []any) any { numIn := fnType.NumIn() if len(args) != numIn { - err := fmt.Sprintf("pool: func params error (args %d, func args %d)", len(args), numIn) + err := fmt.Sprintf("go-events: func params error (args %d, func args %d)", len(args), numIn) panic(err) }