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

264
Visualizações
Try Catch doesnt working when the fetch api returns a 404

Its basically what the title says, my template string in the URL is formatted directly with user input, and if the user inputs incorrectly, the try/catch should catch it and return a 404 and it should console log "Error" while also returning "Error" on the screen, but it doesn't, the Component passes through anyways

import './cssdirect/App.css';
import Daily from './components/daily';
import {useState, useEffect} from 'react'
import Loading from './Loading';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faHeart } from '@fortawesome/free-solid-svg-icons'

function App() {
const [loading, setLoading] = useState(true)
const [city, setCity] = useState('Paris')
const [weatherData, setWeather] = useState([])
const [error, setError] = useState(false)

const getWeather = async() =>{
  setLoading(true)
  setError(false)
  try{
    const resp = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=imperial`)
    const pResp = await resp.json()
    setWeather(pResp)
    setLoading(false)
  }
  catch(err){
    console.log("ERRRRROOOORRRR")
    setError(true)
  }
}

const handleSubmit = (e) =>{
  e.preventDefault()
  console.log(city) 
  getWeather()
}    

useEffect(()=>{
  getWeather()
},[])

  if(loading==true){
    
    return <>
    <h1 className='title'>Monkey Wit Da Weather</h1>
    <Loading/>
   
  }
  else if(error===true){
    return<>
    <h1>Error</h1>
    </>
  }
  else{
    return<>
      <h1 className='title'>Monkey Wit Da Weather</h1>
     <Daily {...weatherData} setCity={setCity} city={city} getWeather={getWeather} handleSubmit={handleSubmit}/>
   
     
    </>
  }
}

export default App;
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Because it is not an error, it will return a Promise. The Promise API proposes the following:

  1. Each asynchronous task will return a promise object.
  2. Each promise object will have a then function that can take two arguments, a success handler and an error handler.
  3. The success or the error handler in the then function will be called only once, after the asynchronous task finishes.
  4. The then function will also return a promise, to allow chaining multiple calls.
  5. Each handler (success or error) can return a value, which will be passed to the next function as an argument, in the chain of promises.
  6. If a handler returns a promise (makes another asynchronous request), then the next handler (success or error) will be called only after that request is finished.

So it will be :

const resp = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=imperial`).then(response => {
      console.log("response:", response)
}).catch(error => {
      console.log("error:", error)
})
about 4 years ago · Juan Pablo Isaza Relatório

0

Per Fetch API:

The Promise returned from fetch() won't reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.

fetch('https://httpstat.us/404')
  .then(function(){
    console.log('200 OK');
  }).catch(function(){
    console.console.log('404');
  })

Above code it won't run into catch block.

You can do something like this:

class FetchError extends Error {
  constructor(response) {
    super(`HTTP error ${response.status}`);
    this.response = response;
  }
}

function fetchSomething(...args) {
  return fetch(...args)
  .then(response => {
    if (!response.ok) {
      throw new FetchError(response);
    }
    return response;
  });
}

You can read more here github/fetch/issues/203

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