You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@spark.apache.org by gu...@apache.org on 2023/11/27 14:41:43 UTC

(spark) branch master updated: [SPARK-46110][PYTHON] Use error classes in catalog, conf, connect, observation, pandas modules

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

gurwls223 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark.git


The following commit(s) were added to refs/heads/master by this push:
     new 7d1db89358e0 [SPARK-46110][PYTHON] Use error classes in catalog, conf, connect, observation, pandas modules
7d1db89358e0 is described below

commit 7d1db89358e0f2d3ddbe751bc53522f5d6e9c693
Author: Hyukjin Kwon <gu...@apache.org>
AuthorDate: Mon Nov 27 23:41:28 2023 +0900

    [SPARK-46110][PYTHON] Use error classes in catalog, conf, connect, observation, pandas modules
    
    ### What changes were proposed in this pull request?
    
    This PR proposes to use error classes in catalog, conf, connect, observation, pandas modules.
    
    ### Why are the changes needed?
    
    For better error handling.
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, it includes the error class, and methods such as `getErrorClass` at the error instance.
    
    ### How was this patch tested?
    
    Existing unittests.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    No.
    
    Closes #44024 from HyukjinKwon/error-calss.
    
    Authored-by: Hyukjin Kwon <gu...@apache.org>
    Signed-off-by: Hyukjin Kwon <gu...@apache.org>
---
 python/pyspark/errors/error_classes.py             | 39 ++++++++++++++++++++--
 python/pyspark/sql/catalog.py                      |  9 ++++-
 python/pyspark/sql/conf.py                         | 15 ++++++---
 python/pyspark/sql/connect/client/artifact.py      | 24 ++++++++++---
 python/pyspark/sql/connect/client/core.py          | 22 +++++++++---
 python/pyspark/sql/connect/conf.py                 | 20 +++++++----
 python/pyspark/sql/connect/conversion.py           | 20 +++++++----
 python/pyspark/sql/connect/observation.py          | 21 +++++++++---
 python/pyspark/sql/connect/plan.py                 | 21 ++++++++----
 python/pyspark/sql/connect/session.py              | 34 +++++++++----------
 python/pyspark/sql/connect/types.py                | 12 +++++--
 python/pyspark/sql/observation.py                  | 11 ++++--
 python/pyspark/sql/pandas/group_ops.py             |  8 +++--
 .../sql/tests/connect/test_connect_basic.py        | 15 +++++----
 .../sql/tests/pandas/test_pandas_grouped_map.py    | 12 +++----
 python/pyspark/sql/tests/test_dataframe.py         |  4 +--
 16 files changed, 209 insertions(+), 78 deletions(-)

diff --git a/python/pyspark/errors/error_classes.py b/python/pyspark/errors/error_classes.py
index 72ee0a53460f..6662efa8ca54 100644
--- a/python/pyspark/errors/error_classes.py
+++ b/python/pyspark/errors/error_classes.py
@@ -76,7 +76,7 @@ ERROR_CLASSES_JSON = """
   },
   "CANNOT_BE_NONE": {
     "message": [
-      "Argument `<arg_name>` can not be None."
+      "Argument `<arg_name>` cannot be None."
     ]
   },
   "CANNOT_CONVERT_COLUMN_INTO_BOOL": {
@@ -277,6 +277,11 @@ ERROR_CLASSES_JSON = """
       "All items in `<arg_name>` should be in <allowed_types>, got <item_type>."
     ]
   },
+  "INVALID_MULTIPLE_ARGUMENT_CONDITIONS" : {
+    "message" : [
+      "[{arg_names}] cannot be <condition>."
+    ]
+  },
   "INVALID_NDARRAY_DIMENSION": {
     "message": [
       "NumPy array input should be of <dimensions> dimensions."
@@ -297,6 +302,11 @@ ERROR_CLASSES_JSON = """
       "Pandas UDF should return StructType for <eval_type>, got <return_type>."
     ]
   },
+  "INVALID_SESSION_UUID_ID": {
+    "message": [
+      "Parameter value <arg_name> must be a valid UUID format: <origin>"
+    ]
+  },
   "INVALID_TIMEOUT_TIMESTAMP" : {
     "message" : [
       "Timeout timestamp (<timestamp>) cannot be earlier than the current watermark (<watermark>)."
@@ -612,6 +622,11 @@ ERROR_CLASSES_JSON = """
       "Argument `<arg_name>` should be a str, got <arg_type>."
     ]
   },
+  "NOT_STRUCT" : {
+    "message" : [
+      "Argument `<arg_name>` should be a struct type, got <arg_type>."
+    ]
+  },
   "NOT_STR_OR_LIST_OF_RDD" : {
     "message" : [
       "Argument `<arg_name>` should be a str or list[RDD], got <arg_type>."
@@ -619,7 +634,7 @@ ERROR_CLASSES_JSON = """
   },
   "NOT_STR_OR_STRUCT" : {
     "message" : [
-      "Argument `<arg_name>` should be a str or structType, got <arg_type>."
+      "Argument `<arg_name>` should be a str or struct type, got <arg_type>."
     ]
   },
   "NOT_WINDOWSPEC" : {
@@ -637,6 +652,11 @@ ERROR_CLASSES_JSON = """
       "No active Spark session found. Please create a new Spark session before running the code."
     ]
   },
+  "NO_SCHEMA_AND_DRIVER_DEFAULT_SCHEME" : {
+    "message" : [
+      "Only allows <arg_name> to be a path without scheme, and Spark Driver should use the default scheme to determine the destination file system."
+    ]
+  },
   "ONLY_ALLOWED_FOR_SINGLE_COLUMN" : {
     "message" : [
       "Argument `<arg_name>` can only be provided for a single column."
@@ -713,6 +733,11 @@ ERROR_CLASSES_JSON = """
       "Cannot start a remote Spark session because there is a regular Spark session already running."
     ]
   },
+  "SESSION_NEED_CONN_STR_OR_BUILDER" : {
+    "message" : [
+      "Needs either connection string or channelBuilder (mutually exclusive) to create a new SparkSession."
+    ]
+  },
   "SESSION_NOT_SAME" : {
     "message" : [
       "Both Datasets must belong to the same SparkSession."
@@ -758,6 +783,11 @@ ERROR_CLASSES_JSON = """
       "Expected <expected> values for `<item>`, got <actual>."
     ]
   },
+  "TYPE_HINT_REQUIRED" : {
+    "message" : [
+      "A <arg_type> is required <where>."
+    ]
+  },
   "UDF_RETURN_TYPE" : {
     "message" : [
       "Return type of the user-defined function should be <expected>, but is <actual>."
@@ -878,6 +908,11 @@ ERROR_CLASSES_JSON = """
       "<feature> is not supported with Arrow optimization enabled in Python UDFs. Disable 'spark.sql.execution.pythonUDF.arrow.enabled' to workaround.."
     ]
   },
+  "VALUE_ALLOWED" : {
+    "message" : [
+      "Value for `<arg_name>` does not allow <disallowed_value>."
+    ]
+  },
   "VALUE_NOT_ACCESSIBLE": {
     "message": [
       "Value `<value>` cannot be accessed inside tasks."
diff --git a/python/pyspark/sql/catalog.py b/python/pyspark/sql/catalog.py
index 1886f810ce05..b5337734b3b8 100644
--- a/python/pyspark/sql/catalog.py
+++ b/python/pyspark/sql/catalog.py
@@ -19,6 +19,7 @@ import sys
 import warnings
 from typing import Any, Callable, NamedTuple, List, Optional, TYPE_CHECKING
 
+from pyspark.errors import PySparkTypeError
 from pyspark.storagelevel import StorageLevel
 from pyspark.sql.dataframe import DataFrame
 from pyspark.sql.session import SparkSession
@@ -851,7 +852,13 @@ class Catalog:
             df = self._jcatalog.createTable(tableName, source, description, options)
         else:
             if not isinstance(schema, StructType):
-                raise TypeError("schema should be StructType")
+                raise PySparkTypeError(
+                    error_class="NOT_STRUCT",
+                    message_parameters={
+                        "arg_name": "schema",
+                        "arg_type": type(schema).__name__,
+                    },
+                )
             scala_datatype = self._jsparkSession.parseDataType(schema.json())
             df = self._jcatalog.createTable(tableName, source, scala_datatype, description, options)
         return DataFrame(df, self._sparkSession)
diff --git a/python/pyspark/sql/conf.py b/python/pyspark/sql/conf.py
index b2dda115f666..e77039565dd1 100644
--- a/python/pyspark/sql/conf.py
+++ b/python/pyspark/sql/conf.py
@@ -22,6 +22,7 @@ from py4j.java_gateway import JavaObject
 
 from pyspark import _NoValue
 from pyspark._globals import _NoValueType
+from pyspark.errors import PySparkTypeError
 
 
 class RuntimeConfig:
@@ -84,12 +85,12 @@ class RuntimeConfig:
         >>> spark.conf.get("my_key")
         'my_value'
         """
-        self._checkType(key, "key")
+        self._check_type(key, "key")
         if default is _NoValue:
             return self._jconf.get(key)
         else:
             if default is not None:
-                self._checkType(default, "default")
+                self._check_type(default, "default")
             return self._jconf.get(key, default)
 
     def unset(self, key: str) -> None:
@@ -116,11 +117,15 @@ class RuntimeConfig:
         """
         self._jconf.unset(key)
 
-    def _checkType(self, obj: Any, identifier: str) -> None:
+    def _check_type(self, obj: Any, identifier: str) -> None:
         """Assert that an object is of type str."""
         if not isinstance(obj, str):
-            raise TypeError(
-                "expected %s '%s' to be a string (was '%s')" % (identifier, obj, type(obj).__name__)
+            raise PySparkTypeError(
+                error_class="NOT_STR",
+                message_parameters={
+                    "arg_name": identifier,
+                    "arg_type": type(obj).__name__,
+                },
             )
 
     def isModifiable(self, key: str) -> bool:
diff --git a/python/pyspark/sql/connect/client/artifact.py b/python/pyspark/sql/connect/client/artifact.py
index 5829ec9a8d4d..46c2b2750ba5 100644
--- a/python/pyspark/sql/connect/client/artifact.py
+++ b/python/pyspark/sql/connect/client/artifact.py
@@ -14,6 +14,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 #
+from pyspark.errors import PySparkRuntimeError, PySparkValueError
 from pyspark.sql.connect.utils import check_dependencies
 from pyspark.sql.connect.client.logging import logger
 
@@ -112,7 +113,10 @@ class Artifact:
         if isinstance(self.storage, LocalData):
             return self.storage.size
         else:
-            raise RuntimeError(f"Unsupported storage {type(self.storage)}")
+            raise PySparkRuntimeError(
+                error_class="UNSUPPORTED_OPERATION",
+                message_parameters={"operation": f"{self.storage} storage"},
+            )
 
 
 def new_jar_artifact(file_name: str, storage: LocalData) -> Artifact:
@@ -214,7 +218,13 @@ class ArtifactManager:
                     # Minimal fix for the workaround of fragment handling in URI.
                     # This has a limitation - hash(#) in the file name would not work.
                     if "#" in local_path:
-                        raise ValueError("'#' in the path is not supported for adding an archive.")
+                        raise PySparkValueError(
+                            error_class="VALUE_ALLOWED",
+                            message_parameters={
+                                "arg_name": "artifact path",
+                                "disallowed_value": "#",
+                            },
+                        )
                     name = f"{name}#{parsed.fragment}"
 
                 artifact = new_archive_artifact(name, LocalFile(local_path))
@@ -223,9 +233,15 @@ class ArtifactManager:
             elif name.endswith(".jar"):
                 artifact = new_jar_artifact(name, LocalFile(local_path))
             else:
-                raise RuntimeError(f"Unsupported file format: {local_path}")
+                raise PySparkRuntimeError(
+                    error_class="UNSUPPORTED_OPERATION",
+                    message_parameters={"operation": f"{local_path} file format"},
+                )
             return [artifact]
-        raise RuntimeError(f"Unsupported scheme: {parsed.scheme}")
+        raise PySparkRuntimeError(
+            error_class="UNSUPPORTED_OPERATION",
+            message_parameters={"operation": f"{parsed.scheme} scheme"},
+        )
 
     def _parse_forward_to_fs_artifacts(self, local_path: str, dest_path: str) -> List[Artifact]:
         abs_path: Path = Path(local_path).absolute()
diff --git a/python/pyspark/sql/connect/client/core.py b/python/pyspark/sql/connect/client/core.py
index 5d8db69c641f..f037e968be01 100644
--- a/python/pyspark/sql/connect/client/core.py
+++ b/python/pyspark/sql/connect/client/core.py
@@ -327,7 +327,10 @@ class ChannelBuilder:
             try:
                 uuid.UUID(session_id, version=4)
             except ValueError as ve:
-                raise ValueError("Parameter value 'session_id' must be a valid UUID format.", ve)
+                raise PySparkValueError(
+                    error_class="INVALID_SESSION_UUID_ID",
+                    message_parameters={"arg_name": "session_id", "origin": str(ve)},
+                )
         return session_id
 
     def toChannel(self) -> grpc.Channel:
@@ -1461,11 +1464,22 @@ class SparkConnectClient(object):
         """
         spark_job_tags_sep = ","
         if tag is None:
-            raise ValueError("Spark Connect tag cannot be null.")
+            raise PySparkValueError(
+                error_class="CANNOT_BE_NONE", message_paramters={"arg_name": "Spark Connect tag"}
+            )
         if spark_job_tags_sep in tag:
-            raise ValueError(f"Spark Connect tag cannot contain '{spark_job_tags_sep}'.")
+            raise PySparkValueError(
+                error_class="VALUE_ALLOWED",
+                message_parameters={
+                    "arg_name": "Spark Connect tag",
+                    "disallowed_value": spark_job_tags_sep,
+                },
+            )
         if len(tag) == 0:
-            raise ValueError("Spark Connect tag cannot be an empty string.")
+            raise PySparkValueError(
+                error_class="VALUE_NOT_NON_EMPTY_STR",
+                message_parameters={"arg_name": "Spark Connect tag", "arg_value": tag},
+            )
 
     def _handle_error(self, error: Exception) -> NoReturn:
         """
diff --git a/python/pyspark/sql/connect/conf.py b/python/pyspark/sql/connect/conf.py
index 16e992044b26..3548a31fef03 100644
--- a/python/pyspark/sql/connect/conf.py
+++ b/python/pyspark/sql/connect/conf.py
@@ -14,6 +14,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 #
+from pyspark.errors import PySparkValueError, PySparkTypeError
 from pyspark.sql.connect.utils import check_dependencies
 
 check_dependencies(__name__)
@@ -79,21 +80,28 @@ class RuntimeConf:
     def isModifiable(self, key: str) -> bool:
         op_is_modifiable = proto.ConfigRequest.IsModifiable(keys=[key])
         operation = proto.ConfigRequest.Operation(is_modifiable=op_is_modifiable)
-        result = self._client.config(operation)
-        if result.pairs[0][1] == "true":
+        result = self._client.config(operation).pairs[0][1]
+        if result == "true":
             return True
-        elif result.pairs[0][1] == "false":
+        elif result == "false":
             return False
         else:
-            raise ValueError(f"Unknown boolean value: {result.pairs[0][1]}")
+            raise PySparkValueError(
+                error_class="VALUE_NOT_ALLOWED",
+                message_parameters={"arg_name": "result", "allowed_values": "'true' or 'false'"},
+            )
 
     isModifiable.__doc__ = PySparkRuntimeConfig.isModifiable.__doc__
 
     def _checkType(self, obj: Any, identifier: str) -> None:
         """Assert that an object is of type str."""
         if not isinstance(obj, str):
-            raise TypeError(
-                "expected %s '%s' to be a string (was '%s')" % (identifier, obj, type(obj).__name__)
+            raise PySparkTypeError(
+                error_class="NOT_STR",
+                message_parameters={
+                    "arg_name": identifier,
+                    "arg_type": type(obj).__name__,
+                },
             )
 
 
diff --git a/python/pyspark/sql/connect/conversion.py b/python/pyspark/sql/connect/conversion.py
index dc46e68f532f..550978d02f85 100644
--- a/python/pyspark/sql/connect/conversion.py
+++ b/python/pyspark/sql/connect/conversion.py
@@ -14,6 +14,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 #
+from pyspark.errors import PySparkValueError
 from pyspark.sql.connect.utils import check_dependencies
 
 check_dependencies(__name__)
@@ -127,9 +128,12 @@ class LocalDataToArrowConversion:
                             _dict[dedup_field_names[i]] = field_convs[i](value.get(field))
                     else:
                         if len(value) != len(field_names):
-                            raise ValueError(
-                                f"Length mismatch: Expected axis has {len(field_names)} elements, "
-                                f"new values have {len(value)} elements"
+                            raise PySparkValueError(
+                                error_class="AXIS_LENGTH_MISMATCH",
+                                message_parameters={
+                                    "expected_length": str(len(field_names)),
+                                    "actual_length": str(len(value)),
+                                },
                             )
                         for i in range(len(field_names)):
                             _dict[dedup_field_names[i]] = field_convs[i](value[i])
@@ -285,10 +289,14 @@ class LocalDataToArrowConversion:
                     pylist[i].append(column_convs[i](item.get(col)))
             else:
                 if len(item) != len(column_names):
-                    raise ValueError(
-                        f"Length mismatch: Expected axis has {len(column_names)} elements, "
-                        f"new values have {len(item)} elements"
+                    raise PySparkValueError(
+                        error_class="AXIS_LENGTH_MISMATCH",
+                        message_parameters={
+                            "expected_length": str(len(column_names)),
+                            "actual_length": str(len(item)),
+                        },
                     )
+
                 for i in range(len(column_names)):
                     pylist[i].append(column_convs[i](item[i]))
 
diff --git a/python/pyspark/sql/connect/observation.py b/python/pyspark/sql/connect/observation.py
index fcc3c2f828b1..174ab74c2506 100644
--- a/python/pyspark/sql/connect/observation.py
+++ b/python/pyspark/sql/connect/observation.py
@@ -17,7 +17,11 @@
 from typing import Any, Dict, Optional
 import uuid
 
-from pyspark.errors import IllegalArgumentException
+from pyspark.errors import (
+    PySparkTypeError,
+    PySparkValueError,
+    IllegalArgumentException,
+)
 from pyspark.sql.connect.column import Column
 from pyspark.sql.connect.dataframe import DataFrame
 from pyspark.sql.observation import Observation as PySparkObservation
@@ -31,9 +35,15 @@ class Observation:
     def __init__(self, name: Optional[str] = None) -> None:
         if name is not None:
             if not isinstance(name, str):
-                raise TypeError("name should be a string")
+                raise PySparkTypeError(
+                    error_class="NOT_STR",
+                    message_parameters={"arg_name": "name", "arg_type": type(name).__name__},
+                )
             if name == "":
-                raise ValueError("name should not be empty")
+                raise PySparkValueError(
+                    error_class="VALUE_NOT_NON_EMPTY_STR",
+                    message_parameters={"arg_name": "name", "arg_value": name},
+                )
         self._name = name
         self._result: Optional[Dict[str, Any]] = None
 
@@ -46,7 +56,10 @@ class Observation:
             self._name = str(uuid.uuid4())
 
         if df.isStreaming:
-            raise IllegalArgumentException("Observation does not support streaming Datasets")
+            raise IllegalArgumentException(
+                error_class="UNSUPPORTED_OPERATION",
+                message_parameters={"operation": "Streaming DataFrame with Observation"},
+            )
 
         self._result = {}
         return DataFrame(plan.CollectMetrics(df._plan, self, list(exprs)), df._session)
diff --git a/python/pyspark/sql/connect/plan.py b/python/pyspark/sql/connect/plan.py
index 4b18914446db..67a33c2b6cf2 100644
--- a/python/pyspark/sql/connect/plan.py
+++ b/python/pyspark/sql/connect/plan.py
@@ -43,7 +43,7 @@ from pyspark.sql.connect.expressions import (
 from pyspark.sql.connect.types import pyspark_types_to_proto_types, UnparsedDataType
 from pyspark.errors import (
     PySparkTypeError,
-    PySparkNotImplementedError,
+    PySparkValueError,
     PySparkPicklingError,
     IllegalArgumentException,
 )
@@ -1060,9 +1060,9 @@ class SetOperation(LogicalPlan):
         elif self.set_op == "except":
             plan.set_op.set_op_type = proto.SetOperation.SET_OP_TYPE_EXCEPT
         else:
-            raise PySparkNotImplementedError(
+            raise PySparkValueError(
                 error_class="UNSUPPORTED_OPERATION",
-                message_parameters={"feature": self.set_op},
+                message_parameters={"operation": self.set_op},
             )
 
         plan.set_op.is_all = self.is_all
@@ -1699,8 +1699,9 @@ class WriteOperation(LogicalPlan):
                         proto.WriteOperation.SaveTable.TableSaveMethod.TABLE_SAVE_METHOD_INSERT_INTO
                     )
                 else:
-                    raise ValueError(
-                        f"Unknown TestSaveMethod value for DataFrame: {self.table_save_method}"
+                    raise PySparkValueError(
+                        error_class="UNSUPPORTED_OPERATION",
+                        message_parameters={"operation": tsm},
                     )
         elif self.path is not None:
             plan.write_operation.path = self.path
@@ -1716,7 +1717,10 @@ class WriteOperation(LogicalPlan):
             elif wm == "ignore":
                 plan.write_operation.mode = proto.WriteOperation.SaveMode.SAVE_MODE_IGNORE
             else:
-                raise ValueError(f"Unknown SaveMode value for DataFrame: {self.mode}")
+                raise PySparkValueError(
+                    error_class="UNSUPPORTED_OPERATION",
+                    message_parameters={"operation": self.mode},
+                )
         return plan
 
     def print(self, indent: int = 0) -> str:
@@ -1812,7 +1816,10 @@ class WriteOperationV2(LogicalPlan):
             elif wm == "create_or_replace":
                 plan.write_operation_v2.mode = proto.WriteOperationV2.Mode.MODE_CREATE_OR_REPLACE
             else:
-                raise ValueError(f"Unknown Mode value for DataFrame: {self.mode}")
+                raise PySparkValueError(
+                    error_class="UNSUPPORTED_OPERATION",
+                    message_parameters={"operation": self.mode},
+                )
         return plan
 
 
diff --git a/python/pyspark/sql/connect/session.py b/python/pyspark/sql/connect/session.py
index 7c1fef2170ae..0fcd85c033cf 100644
--- a/python/pyspark/sql/connect/session.py
+++ b/python/pyspark/sql/connect/session.py
@@ -194,15 +194,11 @@ class SparkSession:
             has_channel_builder = self._channel_builder is not None
             has_spark_remote = "spark.remote" in self._options
 
-            if has_channel_builder and has_spark_remote:
-                raise ValueError(
-                    "Only one of connection string or channelBuilder "
-                    "can be used to create a new SparkSession."
-                )
-
-            if not has_channel_builder and not has_spark_remote:
-                raise ValueError(
-                    "Needs either connection string or channelBuilder to create a new SparkSession."
+            if (has_channel_builder and has_spark_remote) or (
+                not has_channel_builder and not has_spark_remote
+            ):
+                raise PySparkValueError(
+                    error_class="SESSION_NEED_CONN_STR_OR_BUILDER", message_parameters={}
                 )
 
             if has_channel_builder:
@@ -514,9 +510,8 @@ class SparkSession:
                 if _has_nulltype(_schema):
                     # For cases like createDataFrame([("Alice", None, 80.1)], schema)
                     # we can not infer the schema from the data itself.
-                    raise ValueError(
-                        "Some of types cannot be determined after inferring, "
-                        "a StructType Schema is required in this case"
+                    raise PySparkValueError(
+                        error_class="CANNOT_DETERMINE_TYPE", message_parameters={}
                     )
 
             from pyspark.sql.connect.conversion import LocalDataToArrowConversion
@@ -738,7 +733,13 @@ class SparkSession:
         self, *path: str, pyfile: bool = False, archive: bool = False, file: bool = False
     ) -> None:
         if sum([file, pyfile, archive]) > 1:
-            raise ValueError("'pyfile', 'archive' and/or 'file' cannot be True together.")
+            raise PySparkValueError(
+                error_class="INVALID_MULTIPLE_ARGUMENT_CONDITIONS",
+                message_parameters={
+                    "arg_names": "'pyfile', 'archive' and/or 'file'",
+                    "condition": "True together",
+                },
+            )
         self._client.add_artifacts(*path, pyfile=pyfile, archive=archive, file=file)
 
     addArtifacts.__doc__ = PySparkSession.addArtifacts.__doc__
@@ -754,10 +755,9 @@ class SparkSession:
 
     def copyFromLocalToFs(self, local_path: str, dest_path: str) -> None:
         if urllib.parse.urlparse(dest_path).scheme:
-            raise ValueError(
-                "`spark_session.copyFromLocalToFs` API only allows `dest_path` to be a path "
-                "without scheme, and spark driver uses the default scheme to "
-                "determine the destination file system."
+            raise PySparkValueError(
+                error_class="NO_SCHEMA_AND_DRIVER_DEFAULT_SCHEME",
+                message_parameters={"arg_name": "dest_path"},
             )
         self._client.copy_from_local_to_fs(local_path, dest_path)
 
diff --git a/python/pyspark/sql/connect/types.py b/python/pyspark/sql/connect/types.py
index cd2311e614ee..e8da9f61c665 100644
--- a/python/pyspark/sql/connect/types.py
+++ b/python/pyspark/sql/connect/types.py
@@ -49,7 +49,7 @@ from pyspark.sql.types import (
     NullType,
     UserDefinedType,
 )
-from pyspark.errors import PySparkAssertionError
+from pyspark.errors import PySparkAssertionError, PySparkValueError
 
 import pyspark.sql.connect.proto as pb2
 
@@ -205,7 +205,10 @@ def pyspark_types_to_proto_types(data_type: DataType) -> pb2.DataType:
         data_type_string = data_type.data_type_string
         ret.unparsed.data_type_string = data_type_string
     else:
-        raise Exception(f"Unsupported data type {data_type}")
+        raise PySparkValueError(
+            error_class="UNSUPPORTED_OPERATION",
+            message_parameters={"operation": f"data type {data_type}"},
+        )
     return ret
 
 
@@ -303,4 +306,7 @@ def proto_schema_to_pyspark_data_type(schema: pb2.DataType) -> DataType:
             json_value["serializedClass"] = schema.udt.serialized_python_class
         return UserDefinedType.fromJson(json_value)
     else:
-        raise Exception(f"Unsupported data type {schema}")
+        raise PySparkValueError(
+            error_class="UNSUPPORTED_OPERATION",
+            message_parameters={"operation": f"data type {schema}"},
+        )
diff --git a/python/pyspark/sql/observation.py b/python/pyspark/sql/observation.py
index 19201cdf0f3c..ecb21e8d9084 100644
--- a/python/pyspark/sql/observation.py
+++ b/python/pyspark/sql/observation.py
@@ -19,6 +19,7 @@ from typing import Any, Dict, Optional
 
 from py4j.java_gateway import JavaObject, JVMView
 
+from pyspark.errors import PySparkTypeError, PySparkValueError
 from pyspark.sql import column
 from pyspark.sql.column import Column
 from pyspark.sql.dataframe import DataFrame
@@ -85,9 +86,15 @@ class Observation:
         """
         if name is not None:
             if not isinstance(name, str):
-                raise TypeError("name should be a string")
+                raise PySparkTypeError(
+                    error_class="NOT_STR",
+                    message_parameters={"arg_name": "name", "arg_type": type(name).__name__},
+                )
             if name == "":
-                raise ValueError("name should not be empty")
+                raise PySparkValueError(
+                    error_class="VALUE_NOT_NON_EMPTY_STR",
+                    message_parameters={"arg_name": "name", "arg_value": name},
+                )
         self._name = name
         self._jvm: Optional[JVMView] = None
         self._jo: Optional[JavaObject] = None
diff --git a/python/pyspark/sql/pandas/group_ops.py b/python/pyspark/sql/pandas/group_ops.py
index 56403482b9de..dfe37672c037 100644
--- a/python/pyspark/sql/pandas/group_ops.py
+++ b/python/pyspark/sql/pandas/group_ops.py
@@ -18,6 +18,7 @@ import sys
 from typing import List, Union, TYPE_CHECKING, cast
 import warnings
 
+from pyspark.errors import PySparkValueError
 from pyspark.rdd import PythonEvalType
 from pyspark.sql.column import Column
 from pyspark.sql.dataframe import DataFrame
@@ -97,8 +98,11 @@ class PandasGroupedOpsMixin:
                 != PythonEvalType.SQL_GROUPED_MAP_PANDAS_UDF
             )
         ):
-            raise ValueError(
-                "Invalid udf: the udf argument must be a pandas_udf of type " "GROUPED_MAP."
+            raise PySparkValueError(
+                error_class="INVALID_PANDAS_UDF",
+                message_parameters={
+                    "detail": "the udf argument must be a pandas_udf of type GROUPED_MAP."
+                },
             )
 
         warnings.warn(
diff --git a/python/pyspark/sql/tests/connect/test_connect_basic.py b/python/pyspark/sql/tests/connect/test_connect_basic.py
index 856bcbead19d..fb5eaece7f48 100755
--- a/python/pyspark/sql/tests/connect/test_connect_basic.py
+++ b/python/pyspark/sql/tests/connect/test_connect_basic.py
@@ -704,12 +704,15 @@ class SparkConnectBasicTests(SparkConnectSQLTestCase):
         with self.assertRaises(ParseException):
             self.connect.createDataFrame(data, "col1 magic_type, col2 int, col3 int, col4 int")
 
-        with self.assertRaisesRegex(
-            ValueError,
-            "Length mismatch: Expected axis has 3 elements, new values have 4 elements",
-        ):
+        with self.assertRaises(PySparkValueError) as pe:
             self.connect.createDataFrame(data, "col1 int, col2 int, col3 int")
 
+        self.check_error(
+            exception=pe.exception,
+            error_class="AXIS_LENGTH_MISMATCH",
+            message_parameters={"expected_length": "3", "actual_length": "4"},
+        )
+
     def test_with_local_rows(self):
         # SPARK-41789, SPARK-41810: Test creating a dataframe with list of rows and dictionaries
         rows = [
@@ -3708,9 +3711,7 @@ class ChannelBuilderTests(unittest.TestCase):
         with self.assertRaises(ValueError) as ve:
             chan = ChannelBuilder("sc://host/;session_id=abcd")
             SparkConnectClient(chan)
-        self.assertIn(
-            "Parameter value 'session_id' must be a valid UUID format.", str(ve.exception)
-        )
+        self.assertIn("Parameter value session_id must be a valid UUID format", str(ve.exception))
 
         chan = ChannelBuilder("sc://host/")
         self.assertIsNone(chan.session_id)
diff --git a/python/pyspark/sql/tests/pandas/test_pandas_grouped_map.py b/python/pyspark/sql/tests/pandas/test_pandas_grouped_map.py
index 38650b972eab..5e7e4413ee46 100644
--- a/python/pyspark/sql/tests/pandas/test_pandas_grouped_map.py
+++ b/python/pyspark/sql/tests/pandas/test_pandas_grouped_map.py
@@ -422,21 +422,21 @@ class GroupedApplyInPandasTestsMixin:
     def check_wrong_args(self):
         df = self.data
 
-        with self.assertRaisesRegex(ValueError, "Invalid udf"):
+        with self.assertRaisesRegex(ValueError, "Invalid function"):
             df.groupby("id").apply(lambda x: x)
-        with self.assertRaisesRegex(ValueError, "Invalid udf"):
+        with self.assertRaisesRegex(ValueError, "Invalid function"):
             df.groupby("id").apply(udf(lambda x: x, DoubleType()))
-        with self.assertRaisesRegex(ValueError, "Invalid udf"):
+        with self.assertRaisesRegex(ValueError, "Invalid function"):
             df.groupby("id").apply(sum(df.v))
-        with self.assertRaisesRegex(ValueError, "Invalid udf"):
+        with self.assertRaisesRegex(ValueError, "Invalid function"):
             df.groupby("id").apply(df.v + 1)
         with self.assertRaisesRegex(ValueError, "Invalid function"):
             df.groupby("id").apply(
                 pandas_udf(lambda: 1, StructType([StructField("d", DoubleType())]))
             )
-        with self.assertRaisesRegex(ValueError, "Invalid udf"):
+        with self.assertRaisesRegex(ValueError, "Invalid function"):
             df.groupby("id").apply(pandas_udf(lambda x, y: x, DoubleType()))
-        with self.assertRaisesRegex(ValueError, "Invalid udf.*GROUPED_MAP"):
+        with self.assertRaisesRegex(ValueError, "Invalid function.*GROUPED_MAP"):
             df.groupby("id").apply(pandas_udf(lambda x, y: x, DoubleType(), PandasUDFType.SCALAR))
 
     def test_unsupported_types(self):
diff --git a/python/pyspark/sql/tests/test_dataframe.py b/python/pyspark/sql/tests/test_dataframe.py
index 3b2fb87123eb..52806f4f4a38 100644
--- a/python/pyspark/sql/tests/test_dataframe.py
+++ b/python/pyspark/sql/tests/test_dataframe.py
@@ -995,9 +995,9 @@ class DataFrameTestsMixin:
         self.assertEqual(unnamed_observation.get, dict(rows=3))
 
         # observation requires name (if given) to be non empty string
-        with self.assertRaisesRegex(TypeError, "name should be a string"):
+        with self.assertRaisesRegex(TypeError, "`name` should be a str, got int"):
             Observation(123)
-        with self.assertRaisesRegex(ValueError, "name should not be empty"):
+        with self.assertRaisesRegex(ValueError, "`name` must be a non empty string, got ''."):
             Observation("")
 
         # dataframe.observe requires at least one expr


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@spark.apache.org
For additional commands, e-mail: commits-help@spark.apache.org