-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
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
Insert middleware before/after #794
Comments
You could add a middleware outside of Grape for this purpose, however I would definitely welcome a PR that does |
Adding middleware outside of grape is a great idea, is there an example you can point me to? Adding before/after functionality to grape would I think require quite a bit of refactoring to the way middleware is currently constructed. Regrettably I don't have time to dedicate to formulating a PR, but I'd appreciate it if you'd keep this issue open for when some time does get freed up :) |
@camertron Basically i would put it into a config.ru, like here. |
Gotcha, thanks :) |
For noise purposes, this issue could be closed as it was fixed in #1390. |
Closing, thanks @douglascamata. |
Closing, thanks @douglascamata. |
At the moment, it doesn't appear as if Grape allows inserting middleware at arbitrary points in the middleware stack. Rails, for example, provides
insert_before
andinsert_after
methods for this purpose.In our particular case, we'd like to add custom error handling middleware to our API. Specifically, we'd like to be able to submit all errors to Rollbar (an error aggregator) via the rollbar gem. As far as I can tell, we can't use Grape's built-in error handling for this (i.e. via
rescue_from
) because that may override functionality in the API class. We could also monkey-patch the existing error handling middleware or thebuild_middleware
method inEndpoint
, but monkey-patching is brittle and means we'd have to copy and paste a ton of code. It would be great if we could simply insert our middleware at the top of the middleware stack. That way, it could temporarily bypass the existing error middleware, report the error via rollbar, then either re-raise the exception or return the appropriate rack response and continue up the middleware chain.Since there's currently no way to arbitrarily insert middleware, I've come up with a rather hack-ish solution. It works by wrapping
build_middleware
in the equivalent of an alias method chain. When the new method is invoked, it calls the originalbuild_middleware
method, removes the last item in the chain, and adds it back again at index 0. Clearly not optimal, but it works.Any thoughts, suggestions, improvements? Thanks!
The text was updated successfully, but these errors were encountered: