fix: check response.ok before parsing JSON in fetch calls
Fix JSON parsing errors when server returns non-JSON responses: - Check response.ok before calling response.json() - Add fallback error messages using status text - Apply fix to all fetch calls across 12 components This prevents 'JSON.parse: unexpected character' errors when server returns HTML error pages or other non-JSON responses.
This commit is contained in:
@@ -25,14 +25,20 @@ export function ScheduleGenerator({ tournamentId, teamCount }: ScheduleGenerator
|
||||
method: "POST",
|
||||
})
|
||||
|
||||
const data = await response.json()
|
||||
|
||||
// Check response status first before parsing JSON
|
||||
if (!response.ok) {
|
||||
setError(data.error || "Failed to generate schedule")
|
||||
try {
|
||||
const data = await response.json()
|
||||
setError(data.error || "Failed to generate schedule")
|
||||
} catch {
|
||||
setError(`Failed to generate schedule: ${response.status} ${response.statusText}`)
|
||||
}
|
||||
setIsGenerating(false)
|
||||
return
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
|
||||
setResult({
|
||||
roundsCreated: data.roundsCreated,
|
||||
matchupsCreated: data.matchupsCreated,
|
||||
@@ -58,10 +64,13 @@ export function ScheduleGenerator({ tournamentId, teamCount }: ScheduleGenerator
|
||||
method: "DELETE",
|
||||
})
|
||||
|
||||
const data = await response.json()
|
||||
|
||||
if (!response.ok) {
|
||||
setError(data.error || "Failed to delete schedule")
|
||||
try {
|
||||
const data = await response.json()
|
||||
setError(data.error || "Failed to delete schedule")
|
||||
} catch {
|
||||
setError(`Failed to delete schedule: ${response.status} ${response.statusText}`)
|
||||
}
|
||||
setIsGenerating(false)
|
||||
return
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user