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

208
Visualizações
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 Respostas
Responde à pergunta

0

You can get the body just like usual.

throw await response.json();

will work normally.

about 4 years ago · Juan Pablo Isaza Relatório

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 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