From 248a208af896de857954e8c64f3e32a4c2cf7dc7 Mon Sep 17 00:00:00 2001 From: Mathieu Corbin Date: Fri, 1 Jul 2022 14:14:56 +0200 Subject: [PATCH] Allow to retrieve bindHook errors The original error returned by bindHook is currently lost. I have use cases where I need to access this error details in order to return specific error messages to end users. This commit adds the ability to retrieve the bindHook error from the BindError struct. --- tonic/handler.go | 2 +- tonic/tonic.go | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/tonic/handler.go b/tonic/handler.go index bcb99e8..6664bc6 100644 --- a/tonic/handler.go +++ b/tonic/handler.go @@ -73,7 +73,7 @@ func Handler(h interface{}, status int, options ...func(*Route)) gin.HandlerFunc input := reflect.New(in) // Bind the body with the hook. if err := bindHook(c, input.Interface()); err != nil { - handleError(c, BindError{message: err.Error(), typ: in}) + handleError(c, BindError{message: err.Error(), typ: in, bindHookErr: err}) return } // Bind query-parameters. diff --git a/tonic/tonic.go b/tonic/tonic.go index 8bc9290..95ed72c 100644 --- a/tonic/tonic.go +++ b/tonic/tonic.go @@ -230,6 +230,7 @@ func Tags(tags []string) func(*Route) { // to bind parameters, to differentiate from errors returned // by the handlers. type BindError struct { + bindHookErr error validationErr error message string typ reflect.Type @@ -258,6 +259,11 @@ func (be BindError) ValidationErrors() validator.ValidationErrors { return nil } +// BindHookError returns the error from the bind process. +func (be BindError) BindHookError() error { + return be.bindHookErr +} + // An extractorFunc extracts data from a gin context according to // parameters specified in a field tag. type extractor func(*gin.Context, string) (string, []string, error)