diff --git a/api/src/exceptions/hit-rate-limit.ts b/api/src/exceptions/hit-rate-limit.ts new file mode 100644 index 0000000000..6a7a51f897 --- /dev/null +++ b/api/src/exceptions/hit-rate-limit.ts @@ -0,0 +1,7 @@ +import { BaseException } from './base'; + +export class HitRateLimitException extends BaseException { + constructor(message: string) { + super(message, 429, 'REQUESTS_EXCEEDED'); + } +} diff --git a/api/src/exceptions/index.ts b/api/src/exceptions/index.ts index db7444a24d..d98537e18e 100644 --- a/api/src/exceptions/index.ts +++ b/api/src/exceptions/index.ts @@ -2,6 +2,7 @@ export * from './base'; export * from './collection-not-found'; export * from './field-not-found'; export * from './forbidden'; +export * from './hit-rate-limit'; export * from './invalid-credentials'; export * from './invalid-payload'; export * from './invalid-query'; diff --git a/api/src/middleware/rate-limiter.ts b/api/src/middleware/rate-limiter.ts index 2c3da6b354..c7a1d88576 100644 --- a/api/src/middleware/rate-limiter.ts +++ b/api/src/middleware/rate-limiter.ts @@ -7,6 +7,7 @@ import { RequestHandler } from 'express'; import redis from 'redis'; import { RateLimiterRedis } from 'rate-limiter-flexible'; +import { HitRateLimitException } from '../exceptions'; import env from '../env'; const redisClient = redis.createClient({ @@ -47,14 +48,12 @@ const rateLimiter: RequestHandler = (req, res, next) => { .catch((rejRes) => { if (rejRes instanceof Error) { throw new Error('Redis insurance limiter not set up'); - process.exit(1); } else { // If there is no error, rateLimiterRedis promise rejected with number of ms before next request allowed const secs = Math.round(rejRes.msBeforeNext / 1000) || 1; res.set('Retry-After', String(secs)); res.status(429).send('Too Many Requests'); - throw new Error(`To many requests, retry after ${secs}.`); - process.exit(1); + throw new HitRateLimitException(`To many requests, retry after ${secs}.`); } }); } catch (error) {