Errors in middlewares - must api
be global?
#407
-
The docs states that in order to generate an error in a middleware, I have to know the func MyMiddleware(ctx huma.Context, next func(ctx huma.Context)) {
if ctx.Query("error") == "true" {
huma.WriteErr(
api,
ctx,
http.StatusInternalServerError,
"Some friendly message", fmt.Errorf("error detail"),
)
return
}
next(ctx)
} How can I access It seems to me a better approach would be to make huma middlewares return an optional error instead, and then let huma write out the error like it does for request errors, like so: func MyMiddleware(ctx huma.Context, next func(ctx huma.Context)) *huma.StatusError {
if ctx.Query("error") == "true" {
return huma.Error500InternalServerError("Some friendly message")
}
return next(ctx)
} Or am I missing something? - Could app be part of the huma context? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Just use closures bro. // ...
func main() {
// ...
api.UseMiddleware(MyMiddleware(api))
// ...
}
// ...
func MyMiddleware(api huma.API) func(ctx huma.Context, next func(huma.Context)) {
return func(ctx huma.Context, next func(huma.Context)) {
// ...
huma.WriteErr(api, ctx, http.StatusNotImplemented, http.StatusText(http.StatusNotImplemented))
}
} |
Beta Was this translation helpful? Give feedback.
-
Don't do that. huma reference should not be passed to middleware. This causes issues when multiple async requests hit your middleware |
Beta Was this translation helpful? Give feedback.
Just use closures bro.