title: Firebase HTTP Cloud Function - 500 Server Error, try again
body: <p>I have an HTTP function executed a few times a second (I don't have exact statistics).</p>
  
  <p>Sometimes, the request will return data like intended, and sometimes it will return this error text:</p>
  
  <pre class="lang-html prettyprint-override"><code>&lt;html&gt;&lt;head&gt;
  &lt;meta http-equiv="content-type" content="text/html;charset=utf-8"&gt;
  &lt;title&gt;500 Server Error&lt;/title&gt;
  &lt;/head&gt;
  &lt;body text=#000000 bgcolor=#ffffff&gt;
  &lt;h1&gt;Error: Server Error&lt;/h1&gt;
  &lt;h2&gt;The server encountered an error and could not complete your request.&lt;p&gt;Please try again in 30 seconds.&lt;/h2&gt;
  &lt;h2&gt;&lt;/h2&gt;
  &lt;/body&gt;&lt;/html&gt;
  </code></pre>
  
  <p>When this happens, this tends to happen for all of my HTTP functions. Making the same request 5 minutes later often works.</p>
  
  <p>Now, I could have imagined its an error in my code, but I am using a middleware to catch all errors and respond as JSON!</p>
  
  <p>Here is my exported cloud function:</p>
  
  <pre class="lang-js prettyprint-override"><code>const app = express();
  app.use(cors({origin: true, credentials: true})); // Allow cross-origin requests
  app.get('/', this.reportRequest.bind(this));
  app.use(errorMiddleware); // Handle errors
  
  export const report = functions.https.onRequest(app);
  </code></pre>
  
  <p>And here is the <code>errorMiddleware</code>:</p>
  
  <pre class="lang-js prettyprint-override"><code>export const errorMiddleware: ErrorRequestHandler = async (e, req, res, next) =&gt; {
    const executionId = req.header('function-execution-id');
  
    const message = 'message' in e ? e.message : e;
  
    const code = e.code &amp;&amp; e.code &gt; 200 &amp;&amp; e.code &lt; 600 ? e.code : 500;
    res.status(code).json({message, executionId});
  
    next();
  };
  </code></pre>