Skip to content

Insert middleware before/after #794

Closed
@camertron

Description

@camertron

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 and insert_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 the build_middleware method in Endpoint, 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 original build_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!

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions