@@ -29,8 +29,10 @@ import (
2929 "github.com/gin-gonic/gin"
3030)
3131
32- const GinContextKey = "oapi-codegen/gin-context"
33- const UserDataKey = "oapi-codegen/user-data"
32+ const (
33+ GinContextKey = "oapi-codegen/gin-context"
34+ UserDataKey = "oapi-codegen/user-data"
35+ )
3436
3537// Create validator middleware from a YAML file path
3638func OapiValidatorFromYamlFile (path string ) (gin.HandlerFunc , error ) {
@@ -54,9 +56,13 @@ func OapiRequestValidator(swagger *openapi3.T) gin.HandlerFunc {
5456 return OapiRequestValidatorWithOptions (swagger , nil )
5557}
5658
59+ // ErrorHandler is called when there is an error in validation
60+ type ErrorHandler func (c * gin.Context , message string , statusCode int )
61+
5762// Options to customize request validation. These are passed through to
5863// openapi3filter.
5964type Options struct {
65+ ErrorHandler ErrorHandler
6066 Options openapi3filter.Options
6167 ParamDecoder openapi3filter.ContentParameterDecoder
6268 UserData interface {}
@@ -71,8 +77,14 @@ func OapiRequestValidatorWithOptions(swagger *openapi3.T, options *Options) gin.
7177 return func (c * gin.Context ) {
7278 err := ValidateRequestFromContext (c , router , options )
7379 if err != nil {
74- // note: i am not sure if this is the best way to handle this
75- c .AbortWithStatusJSON (http .StatusBadRequest , gin.H {"error" : err .Error ()})
80+ if options != nil && options .ErrorHandler != nil {
81+ options .ErrorHandler (c , err .Error (), http .StatusBadRequest )
82+ // in case the handler didn't internally call Abort, stop the chain
83+ c .Abort ()
84+ } else {
85+ // note: i am not sure if this is the best way to handle this
86+ c .AbortWithStatusJSON (http .StatusBadRequest , gin.H {"error" : err .Error ()})
87+ }
7688 }
7789 c .Next ()
7890 }
0 commit comments