parseApiError function
- String raw
Parses a raw API error string to extract a more user-friendly message.
This function attempts to decode JSON error responses, or provides fallback messages for common network or server issues.
raw
The raw error string, typically from an API exception.
Returns a user-friendly error message.
Implementation
String parseApiError(String raw) {
String fallback = 'Server unreachable or unexpected error';
try {
final start = raw.indexOf('{');
final end = raw.lastIndexOf('}');
if (start != -1 && end != -1 && end > start) {
String jsonPart = raw.substring(start, end + 1).replaceAll("'", '"');
final decoded = jsonDecode(jsonPart);
if (decoded is Map<String, dynamic>) {
return decoded['detail'] ??
decoded['error'] ??
decoded['data'] ??
jsonEncode(decoded);
}
} else if (raw.contains("404")) {
return "Endpoint not found. Server may be down.";
} else if (raw.contains("SocketException")) {
return "No internet connection or server unreachable.";
} else if (raw.contains("<html")) {
return "Unexpected HTML response. Server may not be ready.";
}
} catch (_) {}
return fallback;
}