Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Big thanks @GoldenretriverYT. my new JS looks like this and works fine

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

>Solution :

You can get the body just like usual.

throw await response.json();

will work normally.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading