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

207
Vistas
how to get the php error message in javascript with fetch

I try to get my customized php error message within the fetch promise in js. but it looks like the basic catch only gives me back the status text from the http response code.

my php is written in symfony

#[Route('/test', name:'test', methods: ['POST'])]
public function test(Request $req): Response
{
  return new JsonResponse(['error' => 'my Cusom Error'], 400);
}

javascript:

let btn = document.getElementById('myButton');
btn.addEventListener('click', function(event){
  const fd = new FormData(); // need it because want to send some files with it later
  fd.append('user', 'myUserName');

  fetch('/test', {method: 'POST', body: fd})
    .then((response) => {
      if(!response.ok){
        throw Error(response.statusText); 
        // how to catch the message returned form the server here?
        // the response object does not have this information
        // using response.error() returns a error that error is not function
        // response.error is undefined and has no information
        // a workaround is using the resposen.json().then((errorData) => {...}) inside here, but looks not fine for me.
      }
      return response.json();
    })
    .then((data) => {
      console.log('data received', data);
    })
    .catch((error) => {
      console.log(error);
    });
});
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can get the body just like usual.

throw await response.json();

will work normally.

about 4 years ago · Juan Pablo Isaza Denunciar

0

My solution looks like this

let btn = document.querySelector('#myButton');
btn.addEventListener('click', (event) => {
  const fd = new FormData();
  fd.append('user', 'myUserName');

  fetch('/test', {method: 'POST', body: fd}
    .then(async (response) => {
      if(!response.ok)
        throw await response.json();
      return response.json();
    })
    .then((data) => {
      console.log('success', data);
    })
    .catch((error) => {
      console.error(error);
    })
});

and it works now. big thanks to GoldenretriverYT

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