Search code examples
javascriptphpsymfonyfetch

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

Solution

  • You can get the body just like usual.

    throw await response.json();
    

    will work normally.