forked from loafle/openapi-generator-original
[go-server] Feat: add required assertions to models (#10068)
* Add RequiredError * Add IsZeroValue helper * Add AssertRequired method to all models * Add AssertRequired call for body param * Regenerate files * Add DisallowUnknownFields * Regenerate samples * Use hasRequired in model to remove unnecessary code * Revert disallowUnknownFields * Use isAdditionalPropertiesTrue for disallowing unknown fields * Updated samples * Fix indent * Add require checks for nested slices * Add new tests * Regenerate samples * Regenerate samples after merging
This commit is contained in:
@@ -10,9 +10,16 @@
|
||||
package petstoreserver
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrTypeAssertionError is thrown when type an interface does not match the asserted type
|
||||
ErrTypeAssertionError = errors.New("unable to assert type")
|
||||
)
|
||||
|
||||
// ParsingError indicates that an error has occurred when parsing request parameters
|
||||
type ParsingError struct {
|
||||
Err error
|
||||
@@ -26,6 +33,15 @@ func (e *ParsingError) Error() string {
|
||||
return e.Err.Error()
|
||||
}
|
||||
|
||||
// RequiredError indicates that an error has occurred when parsing request parameters
|
||||
type RequiredError struct {
|
||||
Field string
|
||||
}
|
||||
|
||||
func (e *RequiredError) Error() string {
|
||||
return fmt.Sprintf("required field '%s' is zero value.", e.Field)
|
||||
}
|
||||
|
||||
// ErrorHandler defines the required method for handling error. You may implement it and inject this into a controller if
|
||||
// you would like errors to be handled differently from the DefaultErrorHandler
|
||||
type ErrorHandler func(w http.ResponseWriter, r *http.Request, err error, result *ImplResponse)
|
||||
@@ -36,6 +52,9 @@ func DefaultErrorHandler(w http.ResponseWriter, r *http.Request, err error, resu
|
||||
if _, ok := err.(*ParsingError); ok {
|
||||
// Handle parsing errors
|
||||
EncodeJSONResponse(err.Error(), func(i int) *int { return &i }(http.StatusBadRequest), map[string][]string{}, w)
|
||||
} else if _, ok := err.(*RequiredError); ok {
|
||||
// Handle missing required errors
|
||||
EncodeJSONResponse(err.Error(), func(i int) *int { return &i }(http.StatusUnprocessableEntity), map[string][]string{}, w)
|
||||
} else {
|
||||
// Handle all other errors
|
||||
EncodeJSONResponse(err.Error(), &result.Code, result.Headers, w)
|
||||
|
||||
Reference in New Issue
Block a user