-
-
Notifications
You must be signed in to change notification settings - Fork 159
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
Logging Errors in Huma Middleware #679
Comments
@bioform I see two options you could use here:
Hope that helps! |
@danielgtaylor I've also wanted the ability to get the error returned from the handler for middleware. I'm new to huma so apologies if this is silly, but would it make sense to add a One thing to note: the error returned from handler is the thing I'd like, rather than the error response sent to the client. Having the actual humaCfg.Transformers = append(humaCfg.Transformers, RecordErrorTransformer)
api := huma.New(humaCfg)
api.Use(RecordErrorMiddleware)
api.Use(ErrorMetricsMiddleware)
// hacky transformer that is called by huma's operation handler, storing errors in the context
func RecordErrorTransformer(ctx huma.Context, status string, v any) (any, error) {
errResponse, ok := v.(error)
if !ok {
return v, nil
}
writeHandlerError(ctx.Context().Value(handlerErrCtxKey{}), errResponse)
return v, nil
}
// adds a key to ctx with a stateful value we can update with error
func RecordErrorMiddleware(ctx huma.Context, next func(huma.Context)) {
next(huma.WithValue(ctx, handlerErrCtxKey{}, &handlerErrState{}))
}
// this is an example of how this is used. If we had `ctx.HandlerError()` it'd be used in the same way
func ErrorMetricsMiddleware(ctx huma.Context, next func(huma.Context)) {
defer () {
err := getHandlerError(ctx.Context().Value(handlerErrCtxKey{}))
if err != nil {
updateErrorMetrics(err)
}
}
next(ctx)
}
// these methods read/write from the mutable value stored in the req context by RecordErrorMiddleware
func getHandlerError(handlerState any) error {}
func writeHandlerError(handlerState any, err error) {} |
I am currently working on a Huma middleware and need assistance with logging errors. Specifically, I would like to log the following:
Although I managed to log HTTP status responses, I have not found a proper way to log input parameters and output errors. Here is the current code snippet I am using:
Is there a general way to configure comprehensive logging in a Huma application, including input parameters and output errors?
The text was updated successfully, but these errors were encountered: