huma icon indicating copy to clipboard operation
huma copied to clipboard

Middleware error handling

Open giraffesyo opened this issue 6 months ago • 1 comments

The docs show how to handle errors in a middleware by using huma.WriteErr here with the following code:

func MyMiddleware(ctx huma.Context, next func(ctx huma.Context)) {
	// If there is a query parameter "error=true", then return an error
	if ctx.Query("error") == "true" {
		huma.WriteErr(api, ctx, http.StatusInternalServerError,
			"Some friendly message", fmt.Errorf("error detail"),
		)
		return
	}

	// Otherwise, just continue as normal.
	next(ctx)
})

However, in this code, api is not passed in or defined. How can the middleware get access to api? Do we need to make another function that returns the middleware function, passing api into that function to make it available?

giraffesyo avatar Jul 02 '25 18:07 giraffesyo

I guess for reusable middleware the factory pattern that you have suggested would be the way to do it.

2002suraj456 avatar Jul 07 '25 06:07 2002suraj456