Intento obtener mi mensaje de error de php personalizado dentro de la promesa de búsqueda en js. pero parece que la captura básica solo me devuelve el texto de estado del código de respuesta http.
mi php está escrito en 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); }); });Puedes obtener el cuerpo como de costumbre.
throw await response.json();funcionará normalmente.
Mi solución se ve así
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); }) });y funciona ahora. muchas gracias a GoldenretriverYT