handleApiError static method
Failure
handleApiError(
- dynamic error
)
Implementation
static Failure handleApiError(dynamic error) {
String message = 'An unknown error occurred';
// String? requestId;
// Dio error with no response: the request never got an HTTP reply
// (connection reset, DNS/TLS failure, timeout). Report which call failed and
// show the user something actionable instead of Dio's raw message.
if (error is DioException &&
error.response == null &&
error.type != DioExceptionType.cancel) {
_reportNetworkFailure(error);
return Failure(_timeoutErrorTypes.contains(error.type)
? _timeoutErrorMessage
: _networkErrorMessage);
}
if (error is DioException) {
final responseData = error.response?.data;
final statusCode = error.response?.statusCode;
if (responseData != null) {
// Handle nested error.message pattern similar to JavaScript
if (responseData is Map<String, dynamic>) {
final errorData = responseData['error'];
if (errorData != null && errorData is Map<String, dynamic> && errorData['message'] != null) {
message = errorData['message'].toString();
} else if (errorData != null) {
message = errorData.toString();
} else if (responseData['error_msg'] != null) {
message = responseData['error_msg'].toString();
} else if (responseData['message'] != null) {
message = responseData['message'].toString();
} else {
message = 'Unexpected error with status: $statusCode';
}
} else {
// If responseData is not a Map, convert it to string
message = responseData.toString();
}
return Failure(message);
} else {
// Handle cases where there's no response data
message = error.message ?? 'Network error occurred';
if (statusCode != null) {
message += ' (Status: $statusCode)';
}
return Failure(message);
}
}
// Handle non-DioException errors
if (error is Exception) {
message = error.toString();
} else {
message = error?.toString() ?? 'An unknown error occurred';
}
return Failure(message);
}