Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

267
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda