huma
huma copied to clipboard
Ability to remove default error schema?
So, I notice that there's ErrorModel schema on my generated swagger. I narrow down the code to this code
// defineErrors extracts possible error responses and defines them on the
// operation op.
func defineErrors(op *Operation, registry Registry) {
exampleErr := NewError(0, "")
errContentType := "application/json"
if ctf, ok := exampleErr.(ContentTypeFilter); ok {
errContentType = ctf.ContentType(errContentType)
}
errType := deref(reflect.TypeOf(exampleErr))
errSchema := registry.Schema(errType, true, getHint(errType, "", "Error"))
for _, code := range op.Errors {
op.Responses[strconv.Itoa(code)] = &Response{
Description: http.StatusText(code),
Content: map[string]*MediaType{
errContentType: {
Schema: errSchema,
},
},
}
}
if len(op.Responses) <= 1 && len(op.Errors) == 0 {
// No errors are defined, so set a default response.
op.Responses["default"] = &Response{
Description: "Error",
Content: map[string]*MediaType{
errContentType: {
Schema: errSchema,
},
},
}
}
}
In here, it enfore creation of the ErrorModel and ErrorDetail. Not mention of the default response too. It was everything under this block.
I manage to make patch for this function with the following approach
//go:build !disable_huma_patch
package routes
import (
"github.com/bouk/monkey"
"github.com/danielgtaylor/huma/v2"
// Required for go:linkname
_ "unsafe"
)
// Patch: disable Huma's internal defineErrors function by replacing it with a
// no-op via monkey patching. This prevents automatic default error responses and
// related schemas from being registered.
//
// This is a hack relying on go:linkname and runtime patching. It is **unsafe**
// and may break with future Go releases. Build with `-tags=disable_huma_patch`
// to opt out.
//
// ⚠️ Do NOT delete this file unless you are replacing the patch via a safer
// method.
//
//go:linkname defineErrors github.com/danielgtaylor/huma/v2.defineErrors
func defineErrors(op *huma.Operation, registry huma.Registry)
func noopDefineErrors(op *huma.Operation, registry huma.Registry) {
}
func init() {
monkey.Patch(defineErrors, noopDefineErrors)
}