Estoy haciendo un script que tiene validación del lado del servidor. Cuando falla la validación, hago que el script arroje una excepción del lado del servidor. Quiero acceder al mensaje en la excepción cuando la respuesta llegue al lado del cliente, pero tengo problemas con eso. Si hago console.log los data , puedo ver la excepción, pero quiero acceder a ella en la catch para poder enviar el mensaje de error a un elemento HTML en la página.
fetch(/* Posting to some PHP script */).then(function(data) { // Logic here when success console.log(data) // Shows error msg when there is an error }).catch(function() { // Error Handling, I want to push the error msg to HTML element here });¿Qué estoy haciendo mal aquí? Gracias
Tira el error. Quedará atrapado en .catch() y puede manipularlo allí
fetch(/* Posting to some PHP script */) .then(function(data) { // Logic here when success console.log(data) // Shows error msg when there is an error if(data.error){ // Or whatever condition you need to detect there's an error throw data.error; // This will be caught in the catch() below } }) .catch(function(err) { // You have your error here with the message from the server, display it in the HTML });