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.
This commit is contained in:
Radosław Gierwiało
2025-11-13 15:59:01 +01:00
parent 7a2f6d07ec
commit ac64afa851

View File

@@ -28,6 +28,17 @@ async function fetchAPI(endpoint, options = {}) {
try { try {
const response = await fetch(url, config); 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(); const data = await response.json();
if (!response.ok) { if (!response.ok) {
@@ -43,6 +54,14 @@ async function fetchAPI(endpoint, options = {}) {
if (error instanceof ApiError) { if (error instanceof ApiError) {
throw error; 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 }); throw new ApiError('Network error', 0, { message: error.message });
} }
} }