parseErrorMessage static method

String parseErrorMessage(
  1. DioException error
)

Implementation

static String parseErrorMessage(DioException error) {
  if (error.type == DioExceptionType.connectionTimeout ||
      error.type == DioExceptionType.sendTimeout ||
      error.type == DioExceptionType.receiveTimeout) {
    return 'Connection timed out. Please check server connectivity.';
  }
  if (error.type == DioExceptionType.cancel) {
    return 'Request was manually cancelled.';
  }
  if (error.type == DioExceptionType.badCertificate) {
    return 'Secure connection failed. Invalid SSL certificate.';
  }
  if (error.type == DioExceptionType.connectionError) {
    return 'Unable to connect to the server. Please check your internet connection or try again later.';
  }

  final response = error.response;
  if (response == null || response.data == null) {
    if (error.type == DioExceptionType.unknown &&
        error.error != null &&
        error.error.toString().contains('SocketException')) {
      return 'Server is unreachable. Please verify you are connected to the internet.';
    }
    return error.message ?? 'An unexpected network error occurred.';
  }

  try {
    final data = response.data;
    if (data is Map<String, dynamic>) {
      if (data.containsKey('message') && data['message'] != null) {
        return data['message'].toString();
      }
      if (data.containsKey('error') && data['error'] != null) {
        return data['error'].toString();
      }
      if (data.containsKey('msg') && data['msg'] != null) {
        return data['msg'].toString();
      }
    }
    if (data is String) {
      if (data.contains('<html>') || data.contains('<head>')) {
        return 'Gateway error or server maintenance (Status: ${response.statusCode}).';
      }
      return data;
    }
  } catch (_) {}

  return 'Unexpected response format (Status: ${response.statusCode}).';
}