Skip to content

feat: add new error handler func with context parm #14

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions oapi_validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
package nethttpmiddleware

import (
"context"
"errors"
"fmt"
"log"
Expand All @@ -19,14 +20,19 @@ import (
// ErrorHandler is called when there is an error in validation
type ErrorHandler func(w http.ResponseWriter, message string, statusCode int)

// ErrorHandlerWithContext is called when there is an error in validation
// If both ErrorHandlerWithContext and ErrorHandler are set, ErrorHandlerWithContext will be used
type ErrorHandlerWithContext func(ctx context.Context, w http.ResponseWriter, message string, statusCode int)

// MultiErrorHandler is called when oapi returns a MultiError type
type MultiErrorHandler func(openapi3.MultiError) (int, error)

// Options to customize request validation, openapi3filter specified options will be passed through.
type Options struct {
Options openapi3filter.Options
ErrorHandler ErrorHandler
MultiErrorHandler MultiErrorHandler
Options openapi3filter.Options
ErrorHandler ErrorHandler
ErrorHandlerWithContext ErrorHandlerWithContext
MultiErrorHandler MultiErrorHandler
// SilenceServersWarning allows silencing a warning for https://github.com/deepmap/oapi-codegen/issues/882 that reports when an OpenAPI spec has `spec.Servers != nil`
SilenceServersWarning bool
}
Expand All @@ -52,8 +58,12 @@ func OapiRequestValidatorWithOptions(swagger *openapi3.T, options *Options) func

// validate request
if statusCode, err := validateRequest(r, router, options); err != nil {
if options != nil && options.ErrorHandler != nil {
options.ErrorHandler(w, err.Error(), statusCode)
if options != nil && (options.ErrorHandlerWithContext != nil || options.ErrorHandler != nil) {
if options.ErrorHandlerWithContext != nil {
options.ErrorHandlerWithContext(r.Context(), w, err.Error(), statusCode)
} else {
options.ErrorHandler(w, err.Error(), statusCode)
}
} else {
http.Error(w, err.Error(), statusCode)
}
Expand Down