Cloudflare worker returns 522 Origin connection timeout instead of executing error handling code

Hello !

I have an async request handler in a cloudflare worker, and it can throw errors.
I want to be able to catch these errors, and return them to the client.

What I tried is

  .catch(err => new Response(err.toString(), {status:500}))
  .then(res => event.respondWith(res))

But it fails with 522 Origin connection timeout, without logging any error to the console.

What am I doing wrong ?

hey @lovasoa do you happened to have a ticket opened regarding this issue ?

In general Error 522 indicates that Cloudflare is unable to reach the origin web server and the request times out.

for your code now, to further debug it, with console.log statements, you can see output

addEventListener("fetch", event => {
  console.log(`Received new request: ${event.request.url}`)

In the meantime have you checked. our docs?

Share with us more info in case that you are still experiencing problems

1 Like

Is this one solution?

     * Respond to the request
     * @param {Request} request
    async function handleRequest(request) {
      //return new Response("OK",{status:200});
      throw new Error("I threw");

    addEventListener('fetch', event => {
      .catch(err => new Response(err.toString(),{status:500})))

Thank you @adaptive, that was the solution !

event.respondWith has to be called synchronously in the event handler. In order to perform asynchronous work, one has to pass a promise to event.respondWith.

1 Like