From 14bae4aef34259de3f1341a952f6b795759b10c0 Mon Sep 17 00:00:00 2001 From: abdulrahman Date: Mon, 1 Jan 2024 12:52:53 +0400 Subject: [PATCH] feature: add ability to handle the binder errors --- auto_binder.go | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/auto_binder.go b/auto_binder.go index 233546f1..374f26fd 100644 --- a/auto_binder.go +++ b/auto_binder.go @@ -6,6 +6,13 @@ import ( "reflect" ) +var ( + defaultAutoBinderErrorHandler = func(ctx *Context, err error) { + ctx.Error(err) + ctx.Abort() + } +) + type binderType func(obj any) error func isFunc(obj any) bool { @@ -75,8 +82,10 @@ func callHandler(rt reflect.Type, rv reflect.Value, ctx *Context, binder binderT // // Example: func MyGetHandler(ctx *gin.Context, request *MyRequest) {} // -// engine.GET("/endpoint", gin.AutoBinder(MyGetHandler)) -func AutoBinder(handler any) HandlerFunc { +// engine.GET("/endpoint", gin.AutoBinder(MyGetHandler)) and you can handel the errors by passing a handler +// +// engine.GET("/endpoint", gin.AutoBinder(MyGetHandler, func(ctx *gin.Context, err error) {})) +func AutoBinder(handler any, errorHandler ...func(*Context, error)) HandlerFunc { rt := reflect.TypeOf(handler) if rt.Kind() != reflect.Func { @@ -88,13 +97,18 @@ func AutoBinder(handler any) HandlerFunc { } return func(ctx *Context) { + selectedErrorHandler := defaultAutoBinderErrorHandler + if len(errorHandler) > 0 && errorHandler[0] != nil { + selectedErrorHandler = errorHandler[0] + } + rt := reflect.TypeOf(handler) rv := reflect.ValueOf(handler) if err := callHandler(rt, rv, ctx, func(obj any) error { return ctx.ShouldBind(obj) }); err != nil { - ctx.Error(err) + selectedErrorHandler(ctx, err) } } }