marielle
marielle

Reputation: 428

Catch Google Cloud function errors in POST

I have this cloud function that append a line to a Google Spreadsheet:

function addLine(req, res) {
  res.set("Access-Control-Allow-Origin", "*");
  if (req.method === "OPTIONS") {
    res.set("Access-Control-Allow-Methods", "POST");
    res.set("Access-Control-Allow-Headers", "Content-Type");
    res.set("Access-Control-Max-Age", "3600");
    return res.status(204).send("");
  }
  const isReqValid = validateReq(req);
  if (!isReqValid) return res.send("Not valid request!"); // <--

  const { body } = req;
  const isBodyValid = validateData(body);
  if (!isBodyValid) return res.send("Not valid payload!"); // <--

  return appendData(body)
    .then(() => res.send("Added line"))
    .catch((err) => {
      res.send("Generic error!");
    });
}

function validateReq(req) {
  if (req.method !== "POST") return false;
  return true;
}

function validateData(data) {
  // do something and return true or false
}

async function appendData(data) {
  const client = await auth.getClient();
  return sheets.spreadsheets.values.append(
    {
      spreadsheetId: ...,
      auth: client,
      range: "A1:B",
      valueInputOption: "RAW",
      resource: { values: [data] },
    },
  );
}

I use it in this way:

async collaborate(data: CollaborateDatum) {
  await post('...cloudfunctions.net/addLine', data)
}

async function post(url, data) {
  return fetch(url, {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(data),
  })
}

How can I "read" the errors Not valid request! and Not valid payload!? Because if I tried to append a line with not valid data, I get status code 200 but in Chrome Dev Tools -> Network -> Response, the response is Not valid payload! but I don't know how to catch this error.

Thanks a lot!

Upvotes: 0

Views: 40

Answers (1)

Nisala
Nisala

Reputation: 1338

You should be able to get any response text that's passed back like this:

let responseText = await (await post('...cloudfunctions.net/addLine', data)).text();

Upvotes: 1

Related Questions