title: Rate-limit exceptions in Express middleware?
body: <p>In an Express.js app, we would like to rate-limit users who hit a certain route too often, but only if they cause a certain exception. Is there a natural way to do this in Express?</p>
  
  <p>Here's more or less what we have now, not rate-limited.</p>
  
  <pre><code>app.get(
      "/api/method", 
      authenticationMiddleware, 
      handler
  );
  </code></pre>
  
  <p>Rate-limiter middleware typically looks like this. It counts accesses, and errors out if the user accessed it too many times, before we even get to the handler.</p>
  
  <pre><code>app.get(
      "/api/method", 
      authenticationMiddleware, 
      rateLimiterMiddleware,   # &lt;--- count, and tell them to go away if over limit
      handler
  );
  </code></pre>
  
  <p>However, we're fine with them accessing it as many times as they want - we just want to bar them if they have recently caused a lot of exceptions. </p>
  
  <p>In Express, Error handlers are supposed to go at the end of the handler chain. </p>
  
  <p>So it seems we have to put the "guard" at the front, and an error-handling "counter" at the end.</p>
  
  <pre><code>app.get(
      "/api/method", 
      authenticationMiddleware, 
      errorIfTooManyExceptionsByUser,   # &lt;--- tell them to go away if over the limit
      handler, 
      countExceptionsForUser            # &lt;--- count
  );
  </code></pre>
  
  <p>This seems inelegant, and also a little tricky since the two parts of rate-limiting middleware have to know a lot about each other. Is there a better way?</p>
  
  <p>Perhaps we could get clever and modify the handler(s), to do the guarding and counting before and after they run?</p>
  
  <pre><code>app.get(
     "/api/method", 
     authenticationMiddleware,
     rateLimitErrors(handler)   # &lt;-- ???
  )
  </code></pre>
  
  <p>Am I missing something or is there a better way to do this?</p>