diff --git a/chatbot.php b/chatbot.php index e3c3ebe..01bf4b5 100644 --- a/chatbot.php +++ b/chatbot.php @@ -55,12 +55,26 @@ headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: messageText }) }); + + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); + } + const data = await response.json(); const botResponse = data.reply || 'Sorry, I could not understand.'; appendMessage(botResponse, 'bot'); + } catch (error) { - console.error('Error:', error); - appendMessage('Sorry, something went wrong.', 'bot'); + console.error('Fetch error:', error); + let errorMessage = 'Sorry, something went wrong. Please try again later.'; + if (error instanceof TypeError) { // Network error + errorMessage = 'Could not connect to the server. Please check your network connection.'; + } else if (error instanceof SyntaxError) { // JSON parsing error + errorMessage = 'Received an invalid response from the server.'; + } else if (error.message.startsWith('HTTP error!')) { + errorMessage = 'There was a problem communicating with the server.'; + } + appendMessage(errorMessage, 'bot'); } };