Skip to content

Commit 29b039c

Browse files
Copilothuangyiirene
andcommitted
Add robust error handling for Accept-Language header parsing
Co-authored-by: huangyiirene <7665279+huangyiirene@users.noreply.github.com>
1 parent 77697eb commit 29b039c

1 file changed

Lines changed: 20 additions & 2 deletions

File tree

app/page.tsx

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,28 @@ function getPreferredLanguage(acceptLanguage: string, availableLanguages: readon
1818
.split(',')
1919
.map(lang => {
2020
const parts = lang.trim().split(';');
21-
const code = parts[0];
22-
const quality = parts[1] ? parseFloat(parts[1].split('=')[1]) : 1.0;
21+
const code = parts[0].trim();
22+
23+
// Skip empty language codes
24+
if (!code) {
25+
return null;
26+
}
27+
28+
// Parse quality value, default to 1.0 if not present or invalid
29+
let quality = 1.0;
30+
if (parts[1]) {
31+
const qPart = parts[1].trim();
32+
if (qPart.startsWith('q=')) {
33+
const parsedQuality = parseFloat(qPart.substring(2));
34+
if (!isNaN(parsedQuality)) {
35+
quality = parsedQuality;
36+
}
37+
}
38+
}
39+
2340
return { code, quality };
2441
})
42+
.filter((lang): lang is { code: string; quality: number } => lang !== null)
2543
.sort((a, b) => b.quality - a.quality);
2644

2745
// Try to find the best match (exact or partial) respecting quality order

0 commit comments

Comments
 (0)