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

255
Vistas
Javascript fetch api use custom error message

I'm looking for a way of handling errors with the native javascript fetch api. Used to use jQuery, but I'm trying to use more native javascript functions.

I found this blog and like the approach: https://learnwithparam.com/blog/how-to-handle-fetch-errors/

fetch(url)
  .then((response) => {
    if (response.status >= 200 && response.status <= 299) {
      return response.json();
    } 

    throw Error(response.statusText);
    
  })
  .then((jsonResponse) => {
    // do whatever you want with the JSON response
  }).catch((error) => {
    // Handle the error
    console.log(error);
  });

However, in the catch I'm getting the statusText that belongs to the HTTP code. For 400 for example Bad request. But that is not wat I want, my call to the server will respond with exactly what is wrong. So I want to use the response body text as a the error. I tried different ways, but I can't get the response body incase the HTTP code is 400. With jQuery I used response.responseJSON.html. But this is not available with the fetch api.

So how can I can use the response body as error code.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The fetch API was designed to work best with async functions. If you can make your outer function async, your code would become:

try {
  const response = await fetch(url);
  if (!response.ok) {
    const text = await response.text();
    throw Error(text);
  }
  
  const jsonResponse = await response.json();
  // do whatever you want with the JSON response
    
} catch (error) {
  console.log(error);
}

Otherwise, it gets a bit more complicated:

fetch(url)
  .then((response) => {
    if (response.ok) {
      return response.json();
    }
    
    return response.text().then((text) => throw Error(text));
  })
  .then((jsonResponse) => {
    // do whatever you want with the JSON response
  }).catch((error) => {
    // Handle the error
    console.log(error);
  });
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