feat: implement centralized human-readable error messaging for Dio exceptions and improve API response parsing
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:real_estate_mobile/config/app_config.dart';
|
||||
@@ -234,15 +235,27 @@ class ApiClient {
|
||||
|
||||
// 1. Try to parse a structured error from the JSON response body
|
||||
if (response != null) {
|
||||
final data = response.data;
|
||||
if (data is Map<String, dynamic>) {
|
||||
final rawMessage = data['message'] ?? data['error'];
|
||||
// response.data can be Map (already decoded), String (raw JSON), or null.
|
||||
Map<String, dynamic>? dataMap;
|
||||
if (response.data is Map<String, dynamic>) {
|
||||
dataMap = response.data as Map<String, dynamic>;
|
||||
} else if (response.data is Map) {
|
||||
dataMap = Map<String, dynamic>.from(response.data as Map);
|
||||
} else if (response.data is String) {
|
||||
try {
|
||||
final decoded = _tryDecodeJson(response.data as String);
|
||||
if (decoded is Map<String, dynamic>) dataMap = decoded;
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
if (dataMap != null) {
|
||||
final rawMessage = dataMap['message'] ?? dataMap['error'];
|
||||
final message = rawMessage is List
|
||||
? (rawMessage).join(', ')
|
||||
: rawMessage?.toString();
|
||||
|
||||
if (message != null && message.isNotEmpty) {
|
||||
final errors = (data['errors'] as List<dynamic>?)
|
||||
final errors = (dataMap['errors'] as List<dynamic>?)
|
||||
?.map((e) => FieldError.fromJson(e as Map<String, dynamic>))
|
||||
.toList() ??
|
||||
[];
|
||||
@@ -275,6 +288,14 @@ class ApiClient {
|
||||
);
|
||||
}
|
||||
|
||||
dynamic _tryDecodeJson(String raw) {
|
||||
try {
|
||||
return jsonDecode(raw);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
String _friendlyMessageFor(DioException error) {
|
||||
// Network-level failures take priority over status codes
|
||||
switch (error.type) {
|
||||
|
||||
Reference in New Issue
Block a user