如何使用 fetch 在 javascript 中获取 php 错误消息

how to get the php error message in javascript with fetch

我尝试在 js 的获取承诺中获取自定义的 php 错误消息。但看起来基本捕获只给我返回来自 http 响应代码的状态文本。

我的php是用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);
    });
});

您可以像往常一样获得 body。

throw await response.json();

将正常工作。

我的解决方案如下所示

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

现在可以使用了。非常感谢 GoldenretriverYT