Skip to content

Commit cc60281

Browse files
committed
Add a little Grape middleware section
1 parent c3c40d3 commit cc60281

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

README.md

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@
7373
- [Before and After](#before-and-after)
7474
- [Anchoring](#anchoring)
7575
- [Using Custom Middleware](#using-custom-middleware)
76+
- [Grape Middleware](#grape-middleware)
7677
- [Rails Middleware](#rails-middleware)
7778
- [Remote IP](#remote-ip)
7879
- [Writing Tests](#writing-tests)
@@ -2557,6 +2558,33 @@ part.
25572558

25582559
## Using Custom Middleware
25592560

2561+
### Grape Middleware
2562+
2563+
You can make a custom middleware by using `Grape::Middleware::Base`.
2564+
It's inherited from some grape official middlewares in fact.
2565+
2566+
For example, you can write a middleware to log application exception.
2567+
2568+
```ruby
2569+
class LoggingError < Grape::Middleware::Base
2570+
def after
2571+
if @api_response[0] == 500
2572+
env['rack.logger'].error("Raised error on #{env['PATH_INFO']}")
2573+
end
2574+
end
2575+
end
2576+
```
2577+
2578+
Your middleware can overwrite application response as follows, except error case.
2579+
2580+
```ruby
2581+
class Overwriter < Grape::Middleware::Base
2582+
def after
2583+
[200, { 'Content-Type' => 'text/plain' }, ['Overwrited.']]
2584+
end
2585+
end
2586+
```
2587+
25602588
### Rails Middleware
25612589

25622590
Note that when you're using Grape mounted on Rails you don't have to use Rails middleware because it's already included into your middleware stack.

0 commit comments

Comments
 (0)