This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a commit to branch 
gh-readonly-queue/main/pr-11507-a041d88b6251d35db099945680e831b8666df6c7
in repository https://gitbox.apache.org/repos/asf/arrow-rs.git

commit 544124a28a9993410a48075268e6623fb697d95d
Author: ZENOTME <[email protected]>
AuthorDate: Sun Nov 8 03:56:49 2026 +0000

    feat(arrow-cast): Distinguish unsupported casts from value conversion 
failures (#11507)
    
    # Which issue does this PR close?
    
    Closes #11468.
    
    # Rationale for this change
    
    Callers cannot distinguish unsupported type conversions from failures to
    convert input values when both return `CastError`. Return
    `InvalidArgumentError` for unsupported source/target type combinations,
    and retain `CastError` for invalid values in supported conversions.
    Callers can use `can_cast_types` to check whether a conversion is
    supported.
    
    # What changes are included in this PR?
    
    - Use `InvalidArgumentError` for unsupported conversions and document
    the public cast and Union extraction error semantics.
    - Replace internal defensive errors with typed array accessors or
    `unreachable!()` where callers guarantee the required types. Checks on
    user-supplied target types remain fallible.
    - Add regression tests for `Boolean -> Date32` with both safe modes, and
    invalid `"x" -> Int32` with `safe = false`; also verify that the safe
    conversion still returns null. Update Map and Struct error expectations.
    - Merge current upstream `main`, preserving the Decimal helper
    relocation and resolving the conflict.
    
    # Are these changes tested?
    
    `cargo test -p arrow-cast` passes (267 unit tests, 172 integration
    tests, 15 doc tests). Workspace Clippy with all targets/features,
    formatting, spelling, and arrow-cast documentation with all features and
    warnings denied pass. `cargo test --workspace` also passes locally
    (using Python 3.12 via `PYO3_PYTHON`). Fork Actions are enabled and [CI
    is
    running](https://github.com/ZENOTME/arrow-rs/actions/runs/42183478702).
    
    # Are there any significant user-facing changes?
    
    Unsupported conversions change error variant and displayed prefix from
    `Cast error:` to `Invalid argument error:`. Supported conversions retain
    their existing value-error and null-handling behavior.
    
    Implementation, tests, and documentation were prepared with OpenAI Codex
    assistance.
---
 arrow-cast/src/cast/decimal.rs    | 12 +++---
 arrow-cast/src/cast/dictionary.rs | 43 +++++---------------
 arrow-cast/src/cast/map.rs        |  4 +-
 arrow-cast/src/cast/mod.rs        | 83 +++++++++++++++++++++++++++++----------
 arrow-cast/src/cast/run_array.rs  | 20 ++++------
 arrow-cast/src/cast/temporal.rs   | 12 +-----
 arrow-cast/src/cast/union.rs      | 13 +++++-
 arrow-cast/tests/cast/map.rs      |  4 +-
 arrow-cast/tests/cast/struct.rs   |  6 +--
 9 files changed, 104 insertions(+), 93 deletions(-)

diff --git a/arrow-cast/src/cast/decimal.rs b/arrow-cast/src/cast/decimal.rs
index ba12c61732..8aef0f418a 100644
--- a/arrow-cast/src/cast/decimal.rs
+++ b/arrow-cast/src/cast/decimal.rs
@@ -640,11 +640,9 @@ pub(crate) fn cast_string_to_decimal<T: DecimalType, 
Offset: OffsetSizeTrait>(
             scale,
             cast_options,
         )?,
-        other => {
-            return Err(ArrowError::ComputeError(format!(
-                "Cannot cast {other:?} to decimal",
-            )));
-        }
+        _ => unreachable!(
+            "cast_to_decimal only calls cast_string_to_decimal for Utf8, 
LargeUtf8, or Utf8View"
+        ),
     };
 
     Ok(Arc::new(result))
@@ -1084,7 +1082,7 @@ where
         Utf8 => value_to_string::<i32>(array, cast_options),
         LargeUtf8 => value_to_string::<i64>(array, cast_options),
         Null => Ok(new_null_array(to_type, array.len())),
-        _ => Err(ArrowError::CastError(format!(
+        _ => Err(ArrowError::InvalidArgumentError(format!(
             "Casting from {from_type} to {to_type} not supported"
         ))),
     }
@@ -1176,7 +1174,7 @@ where
         }
         LargeUtf8 => cast_string_to_decimal::<D, i64>(array, *precision, 
*scale, cast_options),
         Null => Ok(new_null_array(to_type, array.len())),
-        _ => Err(ArrowError::CastError(format!(
+        _ => Err(ArrowError::InvalidArgumentError(format!(
             "Casting from {from_type} to {to_type} not supported"
         ))),
     }
diff --git a/arrow-cast/src/cast/dictionary.rs 
b/arrow-cast/src/cast/dictionary.rs
index 12414f5320..556cbfa2ba 100644
--- a/arrow-cast/src/cast/dictionary.rs
+++ b/arrow-cast/src/cast/dictionary.rs
@@ -184,7 +184,7 @@ fn dictionary_to_dictionary_cast<K: ArrowDictionaryKeyType>(
         UInt32 => Arc::new(DictionaryArray::<UInt32Type>::from(data)),
         UInt64 => Arc::new(DictionaryArray::<UInt64Type>::from(data)),
         _ => {
-            return Err(ArrowError::CastError(format!(
+            return Err(ArrowError::InvalidArgumentError(format!(
                 "Unsupported type {to_index_type} for dictionary index"
             )));
         }
@@ -239,7 +239,7 @@ fn cast_keys_only<K: ArrowDictionaryKeyType>(
         DataType::UInt16 => finish_keys_only::<UInt16Type>(cast_keys, values),
         DataType::UInt32 => finish_keys_only::<UInt32Type>(cast_keys, values),
         DataType::UInt64 => finish_keys_only::<UInt64Type>(cast_keys, values),
-        _ => Err(ArrowError::CastError(format!(
+        _ => Err(ArrowError::InvalidArgumentError(format!(
             "Unsupported type {to_index_type} for dictionary index"
         ))),
     }
@@ -527,7 +527,7 @@ pub(crate) fn cast_to_dictionary<K: ArrowDictionaryKeyType>(
             pack_byte_to_fixed_size_dictionary::<K>(array, cast_options, 
byte_size)
         }
         Struct(_) => pack_struct_to_dictionary::<K>(array, dict_value_type, 
cast_options),
-        _ => Err(ArrowError::CastError(format!(
+        _ => Err(ArrowError::InvalidArgumentError(format!(
             "Unsupported output type for dictionary packing: {dict_value_type}"
         ))),
     }
@@ -612,14 +612,9 @@ where
 {
     let dict = pack_numeric_to_dictionary::<K, D>(array, dict_value_type, 
cast_options)?;
     let dict = dict.as_dictionary::<K>();
-    let typed = dict.downcast_dict::<PrimitiveArray<D>>().ok_or_else(|| {
-        ArrowError::ComputeError(format!(
-            "Internal Error: Cannot cast dict to {}Array",
-            D::PREFIX
-        ))
-    })?;
-    let value = typed
+    let value = dict
         .values()
+        .as_primitive::<D>()
         .clone()
         .with_precision_and_scale(precision, scale)?;
     Ok(Arc::new(dict.with_values(Arc::new(value))))
@@ -636,12 +631,7 @@ where
         1024,
         1024,
     );
-    let string_view = array
-        .as_any()
-        .downcast_ref::<StringViewArray>()
-        .ok_or_else(|| {
-            ArrowError::ComputeError("Internal Error: Cannot cast to 
StringViewArray".to_string())
-        })?;
+    let string_view = array.as_string_view();
     for v in string_view {
         match v {
             Some(v) => {
@@ -667,12 +657,7 @@ where
         1024,
         1024,
     );
-    let binary_view = array
-        .as_any()
-        .downcast_ref::<BinaryViewArray>()
-        .ok_or_else(|| {
-            ArrowError::ComputeError("Internal Error: Cannot cast to 
BinaryViewArray".to_string())
-        })?;
+    let binary_view = array.as_binary_view();
     for v in binary_view {
         match v {
             Some(v) => {
@@ -698,12 +683,7 @@ where
     T: ByteArrayType,
 {
     let cast_values = cast_with_options(array, &T::DATA_TYPE, cast_options)?;
-    let values = cast_values
-        .as_any()
-        .downcast_ref::<GenericByteArray<T>>()
-        .ok_or_else(|| {
-            ArrowError::ComputeError("Internal Error: Cannot cast to 
GenericByteArray".to_string())
-        })?;
+    let values = cast_values.as_bytes::<T>();
     let mut b = GenericByteDictionaryBuilder::<K, 
T>::with_capacity(values.len(), 1024, 1024);
     b.append_array(values)?;
     Ok(Arc::new(b.finish()))
@@ -721,12 +701,7 @@ where
 {
     let cast_values =
         cast_with_options(array, &DataType::FixedSizeBinary(byte_width), 
cast_options)?;
-    let values = cast_values
-        .as_any()
-        .downcast_ref::<FixedSizeBinaryArray>()
-        .ok_or_else(|| {
-            ArrowError::ComputeError("Internal Error: Cannot cast to 
GenericByteArray".to_string())
-        })?;
+    let values = cast_values.as_fixed_size_binary();
     let mut b = FixedSizeBinaryDictionaryBuilder::<K>::with_capacity(1024, 
1024, byte_width);
 
     // copy each element one at a time
diff --git a/arrow-cast/src/cast/map.rs b/arrow-cast/src/cast/map.rs
index 4281e677a8..901e3e0082 100644
--- a/arrow-cast/src/cast/map.rs
+++ b/arrow-cast/src/cast/map.rs
@@ -12,9 +12,7 @@ pub(crate) fn cast_map_values(
     to_ordered: bool,
 ) -> Result<ArrayRef, ArrowError> {
     let DataType::Map(entries_field, _) = to_data_type else {
-        return Err(ArrowError::CastError(
-            "Internal Error: to_data_type is not a map type.".to_string(),
-        ));
+        unreachable!("cast_with_options only calls cast_map_values for Map 
target types");
     };
 
     let key_field = key_field(entries_field).ok_or(ArrowError::CastError(
diff --git a/arrow-cast/src/cast/mod.rs b/arrow-cast/src/cast/mod.rs
index e8bf6e2282..47881fc7d9 100644
--- a/arrow-cast/src/cast/mod.rs
+++ b/arrow-cast/src/cast/mod.rs
@@ -461,7 +461,11 @@ pub fn can_cast_types(from_type: &DataType, to_type: 
&DataType) -> bool {
 
 /// Cast `array` to the provided data type and return a new Array with type 
`to_type`, if possible.
 ///
-/// See [`cast_with_options`] for more information
+/// See [`cast_with_options`] for more information.
+///
+/// # Errors
+///
+/// See [cast_with_options](cast_with_options#errors) for error conditions.
 pub fn cast(array: &dyn Array, to_type: &DataType) -> Result<ArrayRef, 
ArrowError> {
     cast_with_options(array, to_type, &CastOptions::default())
 }
@@ -508,6 +512,16 @@ fn cast_reinterpret_arrays<I: ArrowPrimitiveType, O: 
ArrowPrimitiveType<Native =
 /// * `List` to `Primitive`
 /// * `Interval` and `Duration`
 ///
+/// # Errors
+///
+/// Returns [`ArrowError::InvalidArgumentError`] when the conversion between 
the
+/// source and target types is unsupported, regardless of 
[`CastOptions::safe`].
+/// Use [`can_cast_types`] to check whether a conversion is supported.
+///
+/// [`ArrowError::CastError`] reports failures to convert input values, such as
+/// numeric overflow or invalid strings. See [`CastOptions::safe`] for whether
+/// failed conversions produce nulls or errors.
+///
 /// # Durations and Intervals
 ///
 /// Casting integer types directly to interval types such as
@@ -623,7 +637,7 @@ pub fn cast_with_options(
             Int16 => run_end_encoded_cast::<Int16Type>(array, to_type, 
cast_options),
             Int32 => run_end_encoded_cast::<Int32Type>(array, to_type, 
cast_options),
             Int64 => run_end_encoded_cast::<Int64Type>(array, to_type, 
cast_options),
-            _ => Err(ArrowError::CastError(format!(
+            _ => Err(ArrowError::InvalidArgumentError(format!(
                 "Casting from run end encoded type {from_type:?} to 
{to_type:?} not supported",
             ))),
         },
@@ -645,7 +659,7 @@ pub fn cast_with_options(
                     value_type.data_type(),
                     cast_options,
                 ),
-                _ => Err(ArrowError::CastError(format!(
+                _ => Err(ArrowError::InvalidArgumentError(format!(
                     "Casting from type {from_type:?} to run end encoded type 
{to_type:?} not supported",
                 ))),
             }
@@ -655,7 +669,7 @@ pub fn cast_with_options(
             to_type,
             cast_options,
         ),
-        (_, Union(_, _)) => Err(ArrowError::CastError(format!(
+        (_, Union(_, _)) => Err(ArrowError::InvalidArgumentError(format!(
             "Casting from {from_type} to {to_type} not supported"
         ))),
         (Dictionary(index_type, _), _) => match **index_type {
@@ -667,7 +681,7 @@ pub fn cast_with_options(
             UInt16 => dictionary_cast::<UInt16Type>(array, to_type, 
cast_options),
             UInt32 => dictionary_cast::<UInt32Type>(array, to_type, 
cast_options),
             UInt64 => dictionary_cast::<UInt64Type>(array, to_type, 
cast_options),
-            _ => Err(ArrowError::CastError(format!(
+            _ => Err(ArrowError::InvalidArgumentError(format!(
                 "Casting from dictionary type {from_type} to {to_type} not 
supported",
             ))),
         },
@@ -680,7 +694,7 @@ pub fn cast_with_options(
             UInt16 => cast_to_dictionary::<UInt16Type>(array, value_type, 
cast_options),
             UInt32 => cast_to_dictionary::<UInt32Type>(array, value_type, 
cast_options),
             UInt64 => cast_to_dictionary::<UInt64Type>(array, value_type, 
cast_options),
-            _ => Err(ArrowError::CastError(format!(
+            _ => Err(ArrowError::InvalidArgumentError(format!(
                 "Casting from type {from_type} to dictionary type {to_type} 
not supported",
             ))),
         },
@@ -689,7 +703,7 @@ pub fn cast_with_options(
         (LargeList(_), LargeList(to)) => cast_list_values::<i64>(array, to, 
cast_options),
         (FixedSizeList(_, size_from), FixedSizeList(list_to, size_to)) => {
             if size_from != size_to {
-                return Err(ArrowError::CastError(
+                return Err(ArrowError::InvalidArgumentError(
                     "cannot cast fixed-size-list to fixed-size-list with 
different size".into(),
                 ));
             }
@@ -781,7 +795,7 @@ pub fn cast_with_options(
             Utf8 => value_to_string::<i32>(array, cast_options),
             LargeUtf8 => value_to_string::<i64>(array, cast_options),
             Utf8View => value_to_string_view(array, cast_options),
-            dt => Err(ArrowError::CastError(format!(
+            dt => Err(ArrowError::InvalidArgumentError(format!(
                 "Cannot cast LIST to non-list data type {dt}"
             ))),
         },
@@ -1048,10 +1062,10 @@ pub fn cast_with_options(
             to_fields.clone(),
             cast_options,
         ),
-        (Struct(_), _) => Err(ArrowError::CastError(format!(
+        (Struct(_), _) => Err(ArrowError::InvalidArgumentError(format!(
             "Casting from {from_type} to {to_type} not supported"
         ))),
-        (_, Struct(_)) => Err(ArrowError::CastError(format!(
+        (_, Struct(_)) => Err(ArrowError::InvalidArgumentError(format!(
             "Casting from {from_type} to {to_type} not supported"
         ))),
         (_, Boolean) => match from_type {
@@ -1069,7 +1083,7 @@ pub fn cast_with_options(
             Utf8View => cast_utf8view_to_boolean(array, cast_options),
             Utf8 => cast_utf8_to_boolean::<i32>(array, cast_options),
             LargeUtf8 => cast_utf8_to_boolean::<i64>(array, cast_options),
-            _ => Err(ArrowError::CastError(format!(
+            _ => Err(ArrowError::InvalidArgumentError(format!(
                 "Casting from {from_type} to {to_type} not supported",
             ))),
         },
@@ -1088,7 +1102,7 @@ pub fn cast_with_options(
             Utf8View => cast_bool_to_string::<StringViewArray>(array),
             Utf8 => cast_bool_to_string::<StringArray>(array),
             LargeUtf8 => cast_bool_to_string::<LargeStringArray>(array),
-            _ => Err(ArrowError::CastError(format!(
+            _ => Err(ArrowError::InvalidArgumentError(format!(
                 "Casting from {from_type} to {to_type} not supported",
             ))),
         },
@@ -1159,7 +1173,7 @@ pub fn cast_with_options(
             Interval(IntervalUnit::MonthDayNano) => {
                 cast_string_to_month_day_nano_interval::<i32>(array, 
cast_options)
             }
-            _ => Err(ArrowError::CastError(format!(
+            _ => Err(ArrowError::InvalidArgumentError(format!(
                 "Casting from {from_type} to {to_type} not supported",
             ))),
         },
@@ -1217,7 +1231,7 @@ pub fn cast_with_options(
             Interval(IntervalUnit::MonthDayNano) => {
                 cast_view_to_month_day_nano_interval(array, cast_options)
             }
-            _ => Err(ArrowError::CastError(format!(
+            _ => Err(ArrowError::InvalidArgumentError(format!(
                 "Casting from {from_type} to {to_type} not supported",
             ))),
         },
@@ -1292,7 +1306,7 @@ pub fn cast_with_options(
             Interval(IntervalUnit::MonthDayNano) => {
                 cast_string_to_month_day_nano_interval::<i64>(array, 
cast_options)
             }
-            _ => Err(ArrowError::CastError(format!(
+            _ => Err(ArrowError::InvalidArgumentError(format!(
                 "Casting from {from_type} to {to_type} not supported",
             ))),
         },
@@ -1310,7 +1324,7 @@ pub fn cast_with_options(
             Utf8View => Ok(Arc::new(StringViewArray::from(
                 cast_binary_to_string::<i32>(array, 
cast_options)?.as_string::<i32>(),
             ))),
-            _ => Err(ArrowError::CastError(format!(
+            _ => Err(ArrowError::InvalidArgumentError(format!(
                 "Casting from {from_type} to {to_type} not supported",
             ))),
         },
@@ -1329,7 +1343,7 @@ pub fn cast_with_options(
                 let array = cast_binary_to_string::<i64>(array, cast_options)?;
                 Ok(Arc::new(StringViewArray::from(array.as_string::<i64>())))
             }
-            _ => Err(ArrowError::CastError(format!(
+            _ => Err(ArrowError::InvalidArgumentError(format!(
                 "Casting from {from_type} to {to_type} not supported",
             ))),
         },
@@ -1337,7 +1351,7 @@ pub fn cast_with_options(
             Binary => cast_fixed_size_binary_to_binary::<i32>(array, *size),
             LargeBinary => cast_fixed_size_binary_to_binary::<i64>(array, 
*size),
             BinaryView => cast_fixed_size_binary_to_binary_view(array, *size),
-            _ => Err(ArrowError::CastError(format!(
+            _ => Err(ArrowError::InvalidArgumentError(format!(
                 "Casting from {from_type} to {to_type} not supported",
             ))),
         },
@@ -1354,7 +1368,7 @@ pub fn cast_with_options(
             cast_binary_to_string::<i64>(&binary_arr, cast_options)
         }
         (BinaryView, Utf8View) => cast_binary_view_to_string_view(array, 
cast_options),
-        (BinaryView, _) => Err(ArrowError::CastError(format!(
+        (BinaryView, _) => Err(ArrowError::InvalidArgumentError(format!(
             "Casting from {from_type} to {to_type} not supported",
         ))),
         (from_type, Utf8View) if from_type.is_primitive() => {
@@ -1961,7 +1975,7 @@ pub fn cast_with_options(
         (Int32, Interval(IntervalUnit::YearMonth)) => {
             cast_reinterpret_arrays::<Int32Type, IntervalYearMonthType>(array)
         }
-        (_, _) => Err(ArrowError::CastError(format!(
+        (_, _) => Err(ArrowError::InvalidArgumentError(format!(
             "Casting from {from_type} to {to_type} not supported",
         ))),
     }
@@ -2021,6 +2035,35 @@ mod tests {
     use half::f16;
     use std::sync::Arc;
 
+    #[test]
+    fn test_cast_unsupported_types_error() {
+        let array = BooleanArray::from(vec![true, false]);
+        assert!(!can_cast_types(array.data_type(), &Date32));
+        for safe in [true, false] {
+            let options = CastOptions {
+                safe,
+                ..Default::default()
+            };
+            let error = cast_with_options(&array, &Date32, 
&options).unwrap_err();
+            assert!(matches!(error, ArrowError::InvalidArgumentError(_)));
+        }
+    }
+
+    #[test]
+    fn test_cast_invalid_value_error() {
+        let array = StringArray::from(vec!["x"]);
+        assert!(can_cast_types(array.data_type(), &Int32));
+        let options = CastOptions {
+            safe: false,
+            ..Default::default()
+        };
+        let error = cast_with_options(&array, &Int32, &options).unwrap_err();
+        assert!(matches!(error, ArrowError::CastError(_)));
+
+        let result = cast(&array, &Int32).unwrap();
+        assert!(result.is_null(0));
+    }
+
     /// Checks the fast-path classification against `num_cast` for every pair 
of
     /// numeric types. `num_cast` fails only on values outside the target's 
range,
     /// so each type's extremes decide, plus NaN for floats.
diff --git a/arrow-cast/src/cast/run_array.rs b/arrow-cast/src/cast/run_array.rs
index 1b2b68132f..6a46499bd3 100644
--- a/arrow-cast/src/cast/run_array.rs
+++ b/arrow-cast/src/cast/run_array.rs
@@ -14,10 +14,7 @@ pub(crate) fn run_end_encoded_cast<K: RunEndIndexType>(
 ) -> Result<ArrayRef, ArrowError> {
     match array.data_type() {
         DataType::RunEndEncoded(_, _) => {
-            let run_array = array
-                .as_any()
-                .downcast_ref::<RunArray<K>>()
-                .ok_or_else(|| ArrowError::CastError("Expected 
RunArray".to_string()))?;
+            let run_array = array.as_run::<K>();
 
             match to_type {
                 // Stay as RunEndEncoded, cast only the values
@@ -50,7 +47,7 @@ pub(crate) fn run_end_encoded_cast<K: RunEndIndexType>(
                             Arc::new(RunArray::<Int64Type>::try_new(re, 
cast_values.as_ref())?)
                         }
                         _ => {
-                            return Err(ArrowError::CastError(
+                            return Err(ArrowError::InvalidArgumentError(
                                 "Run-end type must be i16, i32, or 
i64".to_string(),
                             ));
                         }
@@ -87,10 +84,9 @@ pub(crate) fn run_end_encoded_cast<K: RunEndIndexType>(
             }
         }
 
-        _ => Err(ArrowError::CastError(format!(
-            "Cannot cast array of type {:?} to RunEndEncodedArray",
-            array.data_type()
-        ))),
+        _ => unreachable!(
+            "cast_with_options only calls run_end_encoded_cast for 
RunEndEncoded source arrays"
+        ),
     }
 }
 
@@ -122,9 +118,9 @@ pub(crate) fn cast_to_run_end_encoded<K: RunEndIndexType>(
 
     // REE arrays are handled by run_end_encoded_cast
     if let DataType::RunEndEncoded(_, _) = array.data_type() {
-        return Err(ArrowError::CastError(
-            "Source array is already a RunEndEncoded array, should have been 
handled by run_end_encoded_cast".to_string()
-        ));
+        unreachable!(
+            "cast_with_options handles RunEndEncoded source arrays with 
run_end_encoded_cast first"
+        );
     }
 
     // Partition the array to identify runs of consecutive equal values
diff --git a/arrow-cast/src/cast/temporal.rs b/arrow-cast/src/cast/temporal.rs
index dd141440e9..ef6def403d 100644
--- a/arrow-cast/src/cast/temporal.rs
+++ b/arrow-cast/src/cast/temporal.rs
@@ -91,15 +91,7 @@ pub(crate) fn cast_duration_to_interval<D: 
ArrowTemporalType<Native = i64>>(
     array: &dyn Array,
     cast_options: &CastOptions,
 ) -> Result<ArrayRef, ArrowError> {
-    let array = array
-        .as_any()
-        .downcast_ref::<PrimitiveArray<D>>()
-        .ok_or_else(|| {
-            ArrowError::ComputeError(
-                "Internal Error: Cannot cast duration to DurationArray of 
expected type"
-                    .to_string(),
-            )
-        })?;
+    let array = array.as_primitive::<D>();
 
     let scale = match array.data_type() {
         DataType::Duration(TimeUnit::Second) => 1_000_000_000,
@@ -198,7 +190,7 @@ pub(crate) fn cast_timestamp_to_time<T: ArrowTimestampType>(
         DataType::Time64(TimeUnit::Nanosecond) => {
             timestamp_to_time::<T, Time64NanosecondType>(array, cast_options)
         }
-        _ => Err(ArrowError::CastError(format!(
+        _ => Err(ArrowError::InvalidArgumentError(format!(
             "Casting from {} to {to_type} not supported",
             array.data_type()
         ))),
diff --git a/arrow-cast/src/cast/union.rs b/arrow-cast/src/cast/union.rs
index 7e6adaf67f..d00265cb98 100644
--- a/arrow-cast/src/cast/union.rs
+++ b/arrow-cast/src/cast/union.rs
@@ -77,7 +77,16 @@ pub(crate) fn resolve_child_array<'a>(
 /// and casts it to that type.
 ///
 /// Rows where a different child array is active become NULL.
-/// If no child array matches, returns an error.
+///
+/// # Errors
+///
+/// Returns [`ArrowError::InvalidArgumentError`] if no child type can be 
selected for
+/// the target type, or conversion from the selected child type is unsupported.
+///
+/// [`ArrowError::CastError`] indicates that the conversion is supported, but a
+/// value in the selected child array cannot be converted, for example because
+/// of an invalid string format or numeric overflow. When [`CastOptions::safe`]
+/// is `true`, failed values are replaced with nulls where supported.
 ///
 /// # Example
 ///
@@ -123,7 +132,7 @@ pub fn union_extract_by_type(
     };
 
     let Some((type_id, _)) = resolve_child_array(fields, target_type) else {
-        return Err(ArrowError::CastError(format!(
+        return Err(ArrowError::InvalidArgumentError(format!(
             "cannot cast Union with fields {} to {}",
             fields
                 .iter()
diff --git a/arrow-cast/tests/cast/map.rs b/arrow-cast/tests/cast/map.rs
index fff0d831b2..037d496909 100644
--- a/arrow-cast/tests/cast/map.rs
+++ b/arrow-cast/tests/cast/map.rs
@@ -45,7 +45,7 @@ fn test_cast_map_dont_allow_change_of_order() {
 
     let new_array_result = cast(&array, &new_type);
     assert!(!can_cast_types(array.data_type(), &new_type));
-    let Err(ArrowError::CastError(t)) = new_array_result else {
+    let Err(ArrowError::InvalidArgumentError(t)) = new_array_result else {
         panic!();
     };
     assert_eq!(
@@ -92,7 +92,7 @@ fn test_cast_map_dont_allow_when_container_cant_cast() {
 
     let new_array_result = cast(&array, &new_type);
     assert!(!can_cast_types(array.data_type(), &new_type));
-    let Err(ArrowError::CastError(t)) = new_array_result else {
+    let Err(ArrowError::InvalidArgumentError(t)) = new_array_result else {
         panic!();
     };
     assert_eq!(
diff --git a/arrow-cast/tests/cast/struct.rs b/arrow-cast/tests/cast/struct.rs
index e4a364ede3..25eeb6835f 100644
--- a/arrow-cast/tests/cast/struct.rs
+++ b/arrow-cast/tests/cast/struct.rs
@@ -66,7 +66,7 @@ fn test_cast_struct_to_struct() {
     assert!(!can_cast_types(&struct_type, &to_type));
     let result = cast(&struct_array, &to_type);
     assert_eq!(
-        "Cast error: Casting from Boolean to Date32 not supported",
+        "Invalid argument error: Casting from Boolean to Date32 not supported",
         result.unwrap_err().to_string()
     );
 }
@@ -153,7 +153,7 @@ fn test_cast_struct_to_non_struct() {
     let to_type = DataType::Utf8;
     let result = cast(&struct_array, &to_type);
     assert_eq!(
-        r#"Cast error: Casting from Struct("a": non-null Boolean) to Utf8 not 
supported"#,
+        r#"Invalid argument error: Casting from Struct("a": non-null Boolean) 
to Utf8 not supported"#,
         result.unwrap_err().to_string()
     );
 }
@@ -179,7 +179,7 @@ fn test_cast_non_struct_to_struct() {
     let to_type = DataType::Struct(vec![Field::new("a", DataType::Boolean, 
false)].into());
     let result = cast(&array, &to_type);
     assert_eq!(
-        r#"Cast error: Casting from Utf8 to Struct("a": non-null Boolean) not 
supported"#,
+        r#"Invalid argument error: Casting from Utf8 to Struct("a": non-null 
Boolean) not supported"#,
         result.unwrap_err().to_string()
     );
 }

Reply via email to