Debugging

A couple of strategies can be used to debug a script that is not functioning as expected.

Serverless Scripting Sandbox

The easiest way to test most scripts will be to use the serverless scripting sandbox. It allows running a script while receiving log output.

34723472

Return Errors in the Response

If for some reason the sandbox is not suitable for debugging, another strategy is to return errors in the response body or headers. For example:

addEventListener("fetch", event => {
  event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
  try {
    const response = await fetch(request);
    doSomethingBad(response);
    return response;
  } catch (e) {
    // Put error stack in response body
    return new Response(e.stack || e.message, { status: 500 });
  }
}

function doSomethingBad() {
  throw new Error("Something bad");
}

Return Debug Info in Headers

Additional debugging info can also be returned in headers

addEventListener("fetch", event => {
  event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
  const origResponse = await fetch(request);

  // Perform some processing on response
  const x = doSomethingComplicated1(origResponse);
  const response = new Response(doSomethingComplicated2(x), { status: 200 });

  // Save intermediate value in header before returning
  response.headers.set("x-debug-value", x);

  return response;
}

function doSomethingComplicated1() {
  return 1;
}

function doSomethingComplicated2(x) {
  return String(x + 1);
}

What’s Next