Home > other >  How do I catch a 404 response and use it to control program flow?
How do I catch a 404 response and use it to control program flow?

Time:11-04

I have access to two APIs. The first (and better API) responds with 404 for certain types of input. If the first API responds with 404 I want to send a request to the second API.

The log shows this after a 404:

{
insertId: "0987654321"
labels: {2}
logName: "projects/my-awesome-project/logs/cloudfunctions.googleapis.com/cloud-functions"
receiveTimestamp: "2022-11-01T21:41:50.570143002Z"
resource: {2}
textPayload: "Exception from a finished function: HTTPError: Response code 404 (NOT FOUND)"
timestamp: "2022-11-01T21:41:50.251844Z"
trace: "projects/my-awesome-project/traces/1234567890"
}

I'm guessing that the code will look something like this:

try {
  async function callFirstAPI() {
    const response = await got(url, options).json();
    // if successful do stuff with the data

  callFirstAPI();
  }
} catch (error) {
  if (error.textPayload.includes('404') {
    callBackupAPI();
  }
}

What doesn't work is this. Nothing logs when the API throws a 404.

try {
  async function callFirstAPI() {
    const response = await got(url, options).json();
    console.log(response); // nothing logs

  callFirstAPI();
  }
} catch (error) {
  console.error("Error!!! "   error); // nothing logs
}

Is catch not firing because a 404 response isn't considered an error? I.e., the callFirstAPI ran without crashing?

CodePudding user response:

Your function in your try block isn't actually running.

You're just declaring the function, but never invoking it.

Try something like this:

try {
  async function callFirstAPI() {
    const response = await got(url, options).json();
    console.log(response); // nothing logs
  }

  firstCallApi() // NOTE: ADD THIS LINE
} catch (error) {
  console.error("Error!!! "   error); // nothing logs
}

CodePudding user response:

I found my mistake. Here's the working code:

async function callFirstAPI() {
  try {
    const response = await got(url, options).json();
    // if successful do stuff with the data
  } catch (error) {
    await callBackupAPI();
  }
}

callFirstAPI();

I had try in the outer block, async in the middle block, and await in the inner block. The correct syntax is async in the outer block, try in the middle block, and await in the inner block. This is explained near the end of the async function documentation.

I hate to think how many years I've been using the incorrect syntax! This is the first time I've wanted to do something with a 404 response. The code will run with the incorrect syntax, it'll just never go to the catch block, i.e., errors won't be handled.

And the error log doesn't contain 404 so if (error.includes('404') won't do anything. Just put your backup code in the catch block and it'll run, no need for if.

  • Related