app.use(async (ctx, next) => {
try {
await rateLimiter.consume(ctx.ip)
await next()
} catch (rejRes) {
ctx.status = 429
ctx.body = 'Too Many Requests'
// Or you can throw an exception
// ctx.throw(429, 'Too Many Requests')
}
})
I believe we should not try/catch await next(). Only the rateLimiter.consume.
If the next chain of middlewares do throw, and this middleware catch it, Koa will return a 429 Too Many Requests.
I think it may be very confusing for beginners which use this snippet and may not understand why is so.
Therefore, I propose to edit the wiki page with the following:
app.use(async (ctx, next) => {
try {
await rateLimiter.consume(ctx.ip)
} catch (rejRes) {
ctx.status = 429
ctx.body = 'Too Many Requests'
// Or you can throw an exception
// ctx.throw(429, 'Too Many Requests')
return;
}
await next()
})
I tested this behaviors with the following snippet.
```js
const Koa = require('koa');
const app = new Koa();
app.use(async (ctx, next) => {
try {
await next();
}
catch {
ctx.body = 'catched';
}
});
app.use(async ctx => {
throw 'middleware2';
})
app.listen(3001);
```
I effectively get answer `catched`.
Hello!
On this wiki page https://github.com/animir/node-rate-limiter-flexible/wiki/Koa-Middleware
I believe we should not try/catch
await next()
. Only therateLimiter.consume
. If the next chain of middlewares do throw, and this middleware catch it, Koa will return a429 Too Many Requests
.I think it may be very confusing for beginners which use this snippet and may not understand why is so.
Therefore, I propose to edit the wiki page with the following:
I tested this behaviors with the following snippet.
```js const Koa = require('koa'); const app = new Koa(); app.use(async (ctx, next) => { try { await next(); } catch { ctx.body = 'catched'; } }); app.use(async ctx => { throw 'middleware2'; }) app.listen(3001); ``` I effectively get answer `catched`.