Errors in middlewares - must api
be global?
#407
Answered
by
x-user
davidolrik
asked this question in
Q&A
-
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.
Answered by
x-user
Apr 25, 2024
Replies: 1 comment
-
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.
0 replies
Answer selected by
davidolrik
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just use closures bro.