Unhandled Promise Rejection in Cloudflare Workers: Does it surface as a 5xx response?
0 reputation · 11 Mar 2020, 08:13 UTC
0 reputation · 11 Mar 2020, 08:13 UTC
Determine whether an unhandled rejection during a background fetch in a Cloudflare Worker results in a 5xx response that can be captured by alert rules, versus being silently swallowed and logged only.
Workers runtime currently does not retry failed fetches, and alert rules can be tuned to aggregated error counts per minute. The behavior of unhandled rejections is not documented as final, and may change with future runtime releases.
When a Promise returned by fetch is rejected without a catch clause, the runtime may either propagate the rejection to the caller, causing a 5xx response, or suppress it, leaving only a log entry. This distinction affects how alert thresholds should be set to avoid noise.
Yes. An unhandled Promise rejection that is returned from the fetch handler causes the Worker to error and Cloudflare returns a 5xx to the client, typically 502 Bad Gateway. That 5xx is visible in Workers analytics and can be used by alert rules.
\nThe Workers runtime treats any unhandled error in the response promise as a Worker error. The error path is not swallowed; it is propagated to the edge and returned as a 5xx. This is consistent with how synchronous throws in the handler are handled.
\nNo regex is required. Use the built-in 5xx metric.
\nNote: If you attach a .catch that swallows the rejection and then returns a Response, no 5xx is generated and the failure is hidden from alert rules.
\n// Minimal reproduction\naddEventListener('fetch', event => {\n event.respondWith(\n fetch('https://invalid.invalid')\n // no .catch\n );\n});\n\nRequest the Worker and check the HTTP status. Expect 502. Then check Workers Logs for the unhandled rejection entry.
\nFuture runtime releases could change the exact status code mapping, e.g., from 502 to 500. Monitor Cloudflare release notes for error handling changes and re-run the minimal test after runtime updates.
\nOne diagnostic detail that changes the recommendation: Is the rejection occurring in the Promise returned to respondWith, or after you have already returned a Response to the client, e.g., in a background task after the response is committed? Rejections after the response is sent are not reflected in the client status.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.