Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

205
Visualizações
How can i catch a server error with async await in javascript?

So i have a function that fetches data from my API. I set a limit to the requests and when the limit is reached, the server returns a 500 response. When testing in local development, the error is catched and the showLimitReachedAlert function for a popup is triggered. When running the setup with docker (+ nginx) the popup function is not triggered.

How can i modify this function to catch 500 response and trigger the function?

function searchByKeyword() {
  for (let x in networks) {
    let urlParameter = x;
    let network = networks[x];

    async function SearchKeywordForNetwork() {
      let url = `${base}/articles/${urlParameter}/${startDate.value}/${endDate.value}/${searchKeyword.value}`;
      const response = await fetch(url);
      const json = await response.json();
      network.value = json;
    }

    SearchKeywordForNetwork().catch(showLimitReachedAlert);
  }
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

First, you need to actually throw an error, if you want to catch it. Also, note that fetch() does not throw any error if the response has a 500 status code. To implement what you want, you need to check the response, throw an error if you've got a 500, then catch the error. Here's an example:

function searchByKeyword() {
  for (let x in networks) {
    let urlParameter = x;
    let network = networks[x];

    async function SearchKeywordForNetwork() {
      let url = `${base}/articles/${urlParameter}/${startDate.value}/${endDate.value}/${searchKeyword.value}`;
      const response = await fetch(url);
      if (response.status == 500) 
        throw new Error("Got a 500 status code");
      const json = await response.json();
      network.value = json;
    }

    try {
      await SearchKeywordForNetwork()
    } catch (error) {
      showLimitReachedAlert();
    }
  }
}

Only thing that I would add: fetch throws an error if there is a network failure. It could be convenient to throw a custom error and check for the error's type in the catch statement. Otherwise, you'd call the showLimitReachedAlert in both cases.

about 4 years ago · Juan Pablo Isaza Relatório

0

Figured out how to do this. Tested both in the Docker and local version.

function getMostRecentNews() {
  for (let x in networks) {
    let urlParameter = x;
    let network = networks[x];

    async function getToday() {
      let url = `${base}/articles/${urlParameter}`;

      fetch(url)
        .then(async (response) => {
          const json = await response.json();
          network.value = json;

          // check for error response
          if (!response.ok) {
            // const error = (json && json.message) || json.statusText;
            return Promise.reject(error);
          }
        })
        .catch((error) => {
          showLimitReachedAlert();
        });
    }

    getToday();
  }
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda