fix: handle malformed ML service responses
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.7
parent
b81fecaa3f
commit
e84be0d42f
@@ -66,6 +66,12 @@ describe('classifyImage', () => {
|
||||
await expect(classifyImage(makeImageFile())).rejects.toThrow('ML service returned 503: Model is not loaded');
|
||||
});
|
||||
|
||||
test('throws when ML service returns malformed JSON', async () => {
|
||||
mockFetch(async () => new Response('not-json', { status: 200, headers: { 'content-type': 'application/json' } }));
|
||||
|
||||
await expect(classifyImage(makeImageFile())).rejects.toThrow('Invalid ML service JSON response');
|
||||
});
|
||||
|
||||
test('throws when ML service returns an unknown label', async () => {
|
||||
mockFetch(async () => new Response(
|
||||
JSON.stringify({
|
||||
|
||||
@@ -74,6 +74,14 @@ async function parseErrorResponse(response: Response): Promise<string> {
|
||||
return response.statusText || 'Unknown error';
|
||||
}
|
||||
|
||||
async function parsePredictionResponse(response: Response): Promise<MlPredictionResponse> {
|
||||
try {
|
||||
return await response.json() as MlPredictionResponse;
|
||||
} catch (error) {
|
||||
throw new Error('Invalid ML service JSON response');
|
||||
}
|
||||
}
|
||||
|
||||
export async function classifyImage(file: File): Promise<ClassificationResult> {
|
||||
if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
|
||||
throw new Error('File must be JPEG or PNG');
|
||||
@@ -97,7 +105,7 @@ export async function classifyImage(file: File): Promise<ClassificationResult> {
|
||||
throw new Error(`ML service returned ${response.status}: ${message}`);
|
||||
}
|
||||
|
||||
const prediction = await response.json() as MlPredictionResponse;
|
||||
const prediction = await parsePredictionResponse(response);
|
||||
const predictedLabel = assertKnownLabel(prediction.label);
|
||||
const predictedDisease = DISEASE_BY_LABEL.get(predictedLabel)!;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user