首页 > 解决方案 > 如何使用 fetch 在 javascript 中获取 php 错误消息

问题描述

我尝试在 js 的 fetch 承诺中获取我自定义的 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);
    });
});

标签: javascriptphpsymfonyfetch

解决方案


你可以像往常一样得到身体。

throw await response.json();

将正常工作。


推荐阅读