backendMessage property

String get backendMessage

Smart error message extractor. Dynamically captures the backend message (whether it is a String or a JSON Map) at runtime without creating dependencies on underlying HTTP libraries (like Dio).

Implementation

String get backendMessage {
  final err = originalError;
  if (err == null) return message;

  try {
    // Step 1: Check if the object has a 'response' field and it is not null (e.g., DioException)
    // Dart dynamic invocations throw NoSuchMethodError or TypeError if the field does not exist.
    final dynamic dynamicError = err;
    final dynamic response = dynamicError.response;

    if (response != null) {
      final dynamic data = response.data;
      if (data != null) {
        // Scenario A: Backend returns the error as a JSON object containing a 'message' key
        if (data is Map && data.containsKey('message')) {
          return data['message'].toString();
        }
        // Scenario B: Backend returns the error directly as a plain text String
        return data.toString();
      }
    }

    // Step 2: If there is no response, check if the library itself generated an error message (e.g., dioError.message)
    final dynamic msg = dynamicError.message;
    if (msg != null) {
      return msg.toString();
    }
  } catch (_) {
    // If any error occurs during dynamic property resolution (e.g., field not found),
    // it silently falls through to the default message below.
  }

  // Returns the default system message if no specific backend message could be extracted
  // from the originalError.
  return message;
}