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

209
Visualizações
cómo obtener el mensaje de error de php en javascript con fetch

Intento obtener mi mensaje de error de php personalizado dentro de la promesa de búsqueda en js. pero parece que la captura básica solo me devuelve el texto de estado del código de respuesta http.

mi php está escrito en 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 Respostas
Responde à pergunta

0

Puedes obtener el cuerpo como de costumbre.

 throw await response.json();

funcionará normalmente.

about 4 years ago · Juan Pablo Isaza Relatório

0

Mi solución se ve así

 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); }) });

y funciona ahora. muchas gracias a GoldenretriverYT

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