From ac64afa8512e6461208d042b25e2bfa1b1e5b4bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Gierwia=C5=82o?= Date: Thu, 13 Nov 2025 15:59:01 +0100 Subject: [PATCH] fix: improve API error handling for non-JSON responses Enhanced the fetchAPI function to better handle cases when the server returns HTML instead of JSON (e.g., when backend is down and nginx returns 502 Bad Gateway). This prevents confusing error messages like "Unexpected token '<'" and provides clearer feedback to users. Changes: - Check Content-Type header before parsing JSON - Catch SyntaxError from JSON parsing attempts - Provide user-friendly error messages for server issues This fixes the issue where entering WSDC ID 26111 during registration showed a JSON parsing error when the backend wasn't running. --- frontend/src/services/api.js | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/frontend/src/services/api.js b/frontend/src/services/api.js index ace98a8..65d297e 100644 --- a/frontend/src/services/api.js +++ b/frontend/src/services/api.js @@ -28,6 +28,17 @@ async function fetchAPI(endpoint, options = {}) { try { const response = await fetch(url, config); + + // Check if response is JSON before parsing + const contentType = response.headers.get('content-type'); + if (!contentType || !contentType.includes('application/json')) { + throw new ApiError( + 'Server returned non-JSON response', + response.status, + { message: 'The server is not responding correctly. Please try again later.' } + ); + } + const data = await response.json(); if (!response.ok) { @@ -43,6 +54,14 @@ async function fetchAPI(endpoint, options = {}) { if (error instanceof ApiError) { throw error; } + // Handle JSON parsing errors + if (error instanceof SyntaxError) { + throw new ApiError( + 'Invalid server response', + 0, + { message: 'The server returned an invalid response. Please check if the server is running.' } + ); + } throw new ApiError('Network error', 0, { message: error.message }); } }