From 2618e6f7a4479d2343ddae6457b1b103c620f204 Mon Sep 17 00:00:00 2001 From: PRAteek-singHWY Date: Mon, 16 Feb 2026 18:00:16 +0530 Subject: [PATCH] Fix chatbot error handling: specific error messages and login loop fix --- .../frontend/src/pages/chatbot/chatbot.tsx | 36 +++++++++++++++---- 1 file changed, 29 insertions(+), 7 deletions(-) diff --git a/application/frontend/src/pages/chatbot/chatbot.tsx b/application/frontend/src/pages/chatbot/chatbot.tsx index 7ffabdd5..eb1b756a 100644 --- a/application/frontend/src/pages/chatbot/chatbot.tsx +++ b/application/frontend/src/pages/chatbot/chatbot.tsx @@ -2,13 +2,13 @@ import './chatbot.scss'; import DOMPurify, { sanitize } from 'dompurify'; import { marked } from 'marked'; -import React, { useState } from 'react'; +import React, { useEffect, useState } from 'react'; import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter'; import { oneLight } from 'react-syntax-highlighter/dist/esm/styles/prism'; import { Button, Container, Form, GridRow, Header, Icon } from 'semantic-ui-react'; import { Grid } from 'semantic-ui-react'; -import { LoadingAndErrorIndicator } from '../../components/LoadingAndErrorIndicator'; + import { useEnvironment } from '../../hooks'; import { Document } from '../../types'; @@ -61,11 +61,17 @@ export const Chatbot = () => { }) .catch((error) => { console.error('Error checking if user is logged in:', error); - setError(error); + setError(error instanceof Error ? error.message : 'Network error checking login status'); setLoading(false); }); } + useEffect(() => { + if (user === '') { + login(); + } + }, []); + function processResponse(response: string) { const responses = response.split('```'); const res: JSX.Element[] = []; @@ -115,7 +121,22 @@ export const Chatbot = () => { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ prompt: currentTerm }), // ✅ use captured term }) - .then((response) => response.json()) + .then(async (response) => { + if (!response.ok) { + const text = await response.text(); + let errorMessage = response.statusText; + try { + const json = JSON.parse(text); + if (json.error) errorMessage = json.error; + else if (json.message) errorMessage = json.message; + } catch (e) { + // not json, use text if available + if (text) errorMessage = text; + } + throw new Error(errorMessage || `Error ${response.status}`); + } + return response.json(); + }) .then((data) => { setLoading(false); setError(''); @@ -135,7 +156,7 @@ export const Chatbot = () => { }) .catch((error) => { console.error('Error fetching answer:', error); - setError(error); + setError(error instanceof Error ? error.message : 'An unexpected network error occurred'); setLoading(false); }); } @@ -160,7 +181,7 @@ export const Chatbot = () => { return ( <> - {user !== '' ? null : login()} + {/* user login check moved to useEffect */} @@ -172,7 +193,8 @@ export const Chatbot = () => { {' '} {error && (
-
Document could not be loaded
+
Error
+

{error}

)}