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

roryqi pushed a commit to branch branch-1.3
in repository https://gitbox.apache.org/repos/asf/gravitino.git


The following commit(s) were added to refs/heads/branch-1.3 by this push:
     new 335fbdbc20 [Cherry-pick to branch-1.3] [#14302,#14417,#14744,#14421] 
fix(iceberg-rest): Map remaining IRC client errors to 4xx (#14751) (#14853)
335fbdbc20 is described below

commit 335fbdbc202c701955febd460a8ad63da50ad98b
Author: MaSai <[email protected]>
AuthorDate: Wed Nov 11 09:42:41 2026 +0800

    [Cherry-pick to branch-1.3] [#14302,#14417,#14744,#14421] 
fix(iceberg-rest): Map remaining IRC client errors to 4xx (#14751) (#14853)
    
    **Cherry-pick Information:**
    - Original commit: 23042f85a5b865547dbb0fdf85bf1ed339018dbc
    - Target branch: `branch-1.3`
    - Status: ✅ Conflicts resolved
    
    Replaces closed auto cherry-pick #14850.
    
    Co-authored-by: Cursor <[email protected]>
---
 .../iceberg/common/ops/IcebergCatalogWrapper.java  | 55 ++++++++++++++++++---
 .../common/ops/TestIcebergCatalogWrapper.java      | 53 ++++++++++++++++++++
 .../iceberg/service/CatalogWrapperForREST.java     |  9 ++--
 .../iceberg/service/IcebergExceptionMapper.java    |  5 ++
 .../web/filter/RegisterTableAuthzHandler.java      | 18 ++++++-
 .../service/TestIcebergExceptionMapper.java        | 26 ++++++++++
 .../iceberg/service/TestIcebergScanPlanning.java   | 42 ++++++++++++++++
 .../TestIcebergNamespaceOperationExecutor.java     | 21 ++++++++
 .../web/filter/TestRegisterTableAuthzHandler.java  | 57 ++++++++++++++++++++--
 9 files changed, 272 insertions(+), 14 deletions(-)

diff --git 
a/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/ops/IcebergCatalogWrapper.java
 
b/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/ops/IcebergCatalogWrapper.java
index d1d959eeb1..1a847f5877 100644
--- 
a/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/ops/IcebergCatalogWrapper.java
+++ 
b/iceberg/iceberg-common/src/main/java/org/apache/gravitino/iceberg/common/ops/IcebergCatalogWrapper.java
@@ -41,6 +41,7 @@ import 
org.apache.gravitino.iceberg.common.utils.IcebergCatalogUtil;
 import org.apache.gravitino.utils.ClassUtils;
 import org.apache.gravitino.utils.IsolatedClassLoader;
 import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.UnsupportedFileSystemException;
 import org.apache.hadoop.security.UserGroupInformation;
 import org.apache.iceberg.BaseMetadataTable;
 import org.apache.iceberg.BaseTable;
@@ -64,6 +65,7 @@ import org.apache.iceberg.exceptions.BadRequestException;
 import org.apache.iceberg.exceptions.NoSuchTableException;
 import org.apache.iceberg.exceptions.NoSuchViewException;
 import org.apache.iceberg.exceptions.NotFoundException;
+import org.apache.iceberg.exceptions.RuntimeIOException;
 import org.apache.iceberg.io.FileIO;
 import org.apache.iceberg.io.ResolvingFileIO;
 import org.apache.iceberg.jdbc.JdbcCatalog;
@@ -340,16 +342,34 @@ public class IcebergCatalogWrapper implements 
AutoCloseable {
    *
    * @param metadataLocation metadata file location
    * @return parsed table metadata
-   * @throws BadRequestException if no metadata file exists at the location
+   * @throws BadRequestException if the location is missing, not a metadata 
file, or uses a scheme
+   *     the catalog cannot read
+   * @throws RuntimeIOException for other IO failures (storage outage, 
credentials, timeouts)
    */
   public TableMetadata loadTableMetadataFromLocation(String metadataLocation) {
     validateTableLocation(metadataLocation);
+    requireMetadataFileName(metadataLocation);
     try (FileIO fileIO = CatalogUtil.loadFileIO(fileIOImpl(), 
fileIOProperties(), null)) {
-      return TableMetadataParser.read(fileIO, metadataLocation);
-    } catch (NotFoundException e) {
-      // The location comes from the request, so a missing file is a client 
error. 404 is reserved
-      // by the REST spec for a namespace or table that does not exist.
-      throw new BadRequestException("Metadata location %s does not exist", 
metadataLocation);
+      try {
+        return TableMetadataParser.read(fileIO, metadataLocation);
+      } catch (NotFoundException e) {
+        // Request-supplied location missing: client error. 404 is for missing 
namespace/table.
+        LOG.info("Metadata location does not exist: {}", metadataLocation, e);
+        throw new BadRequestException("Metadata location %s does not exist", 
metadataLocation);
+      } catch (RuntimeIOException e) {
+        // Unsupported scheme via cause type (not message text). Walk the 
chain in case FileIO
+        // wraps UnsupportedFileSystemException deeper than getCause(). Other 
IO stays 5xx.
+        for (Throwable t = e; t != null; t = t.getCause()) {
+          if (t instanceof UnsupportedFileSystemException) {
+            LOG.info(
+                "Cannot read metadata location with unsupported scheme: {}", 
metadataLocation, e);
+            throw new BadRequestException(
+                "Cannot read metadata location %s: unsupported or unreadable 
scheme",
+                metadataLocation);
+          }
+        }
+        throw e;
+      }
     }
   }
 
@@ -786,4 +806,27 @@ public class IcebergCatalogWrapper implements 
AutoCloseable {
                   MAX_JDBC_NAMESPACE_PROPERTY_VALUE_LENGTH));
     }
   }
+
+  /**
+   * Same gate as Iceberg {@code TableMetadataParser.read} → {@code 
Codec.fromFileName}: reject
+   * directory / non-metadata paths before reading. Iceberg itself requires 
the path to contain
+   * {@code .metadata.json} (including {@code .metadata.json.gz}); any 
metadata file Iceberg can
+   * load already passes this check, so this is not stricter than Iceberg and 
does not break
+   * existing registered tables. Do not catch {@link IllegalArgumentException} 
around {@code read()}
+   * — corrupt content / {@code fromJson} validation must not be mislabeled as 
a bad
+   * metadata-location.
+   */
+  private static void requireMetadataFileName(String metadataLocation) {
+    if (metadataLocation == null) {
+      throw new BadRequestException(
+          "Metadata location %s is not a valid metadata file", 
metadataLocation);
+    }
+    try {
+      TableMetadataParser.Codec.fromFileName(metadataLocation);
+    } catch (IllegalArgumentException e) {
+      LOG.info("Metadata location is not a valid metadata file: {}", 
metadataLocation, e);
+      throw new BadRequestException(
+          "Metadata location %s is not a valid metadata file", 
metadataLocation);
+    }
+  }
 }
diff --git 
a/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/ops/TestIcebergCatalogWrapper.java
 
b/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/ops/TestIcebergCatalogWrapper.java
index b89328da5f..e02de0cc90 100644
--- 
a/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/ops/TestIcebergCatalogWrapper.java
+++ 
b/iceberg/iceberg-common/src/test/java/org/apache/gravitino/iceberg/common/ops/TestIcebergCatalogWrapper.java
@@ -52,6 +52,7 @@ import org.apache.iceberg.catalog.Namespace;
 import org.apache.iceberg.catalog.TableIdentifier;
 import org.apache.iceberg.exceptions.BadRequestException;
 import org.apache.iceberg.exceptions.NoSuchViewException;
+import org.apache.iceberg.exceptions.RuntimeIOException;
 import org.apache.iceberg.jdbc.JdbcCatalog;
 import org.apache.iceberg.rest.requests.CreateNamespaceRequest;
 import org.apache.iceberg.rest.requests.CreateTableRequest;
@@ -400,6 +401,9 @@ public class TestIcebergCatalogWrapper {
     }
   }
 
+  /**
+   * Request-supplied metadata-location miss on registerTable → BadRequest, 
not Iceberg NotFound.
+   */
   @Test
   public void testRegisterTableWithMissingMetadataIsBadRequest(@TempDir Path 
warehouseDir)
       throws Exception {
@@ -419,6 +423,10 @@ public class TestIcebergCatalogWrapper {
     }
   }
 
+  /**
+   * Request-supplied metadata-location miss on loadTableMetadataFromLocation 
→ BadRequest (used by
+   * register-table authz / executor before register).
+   */
   @Test
   public void testLoadTableMetadataFromMissingLocationIsBadRequest(@TempDir 
Path warehouseDir)
       throws Exception {
@@ -432,6 +440,51 @@ public class TestIcebergCatalogWrapper {
     }
   }
 
+  @Test
+  public void testLoadTableMetadataFromDirectoryIsBadRequest(@TempDir Path 
warehouseDir)
+      throws Exception {
+    try (IcebergCatalogWrapper wrapper =
+        new IcebergCatalogWrapper(new 
IcebergConfig(sqliteConfig(warehouseDir)))) {
+      Path directory = 
Files.createDirectories(warehouseDir.resolve("not-a-metadata-file"));
+      String location = directory.toUri().toString();
+      BadRequestException e =
+          Assertions.assertThrows(
+              BadRequestException.class, () -> 
wrapper.loadTableMetadataFromLocation(location));
+      Assertions.assertTrue(
+          e.getMessage().contains("is not a valid metadata file"), 
e.getMessage());
+    }
+  }
+
+  @Test
+  public void testLoadTableMetadataFromCorruptContentIsNotBadRequest(@TempDir 
Path warehouseDir)
+      throws Exception {
+    try (IcebergCatalogWrapper wrapper =
+        new IcebergCatalogWrapper(new 
IcebergConfig(sqliteConfig(warehouseDir)))) {
+      Path metadataFile = warehouseDir.resolve("v1.metadata.json");
+      Files.writeString(metadataFile, "{not-valid-table-metadata", 
StandardCharsets.UTF_8);
+      String location = metadataFile.toUri().toString();
+      // Codec.fromFileName accepts *.metadata.json; corrupt JSON must not 
become BadRequest.
+      Assertions.assertThrows(
+          RuntimeIOException.class, () -> 
wrapper.loadTableMetadataFromLocation(location));
+    }
+  }
+
+  @Test
+  public void testLoadTableMetadataFromUnreadableSchemeIsBadRequest(@TempDir 
Path warehouseDir)
+      throws Exception {
+    try (IcebergCatalogWrapper wrapper =
+        new IcebergCatalogWrapper(new 
IcebergConfig(sqliteConfig(warehouseDir)))) {
+      // Local JDBC catalogs have no S3 FileIO; the client-supplied scheme is 
unreadable.
+      String location = "s3://bucket/path/v1.metadata.json";
+      BadRequestException e =
+          Assertions.assertThrows(
+              BadRequestException.class, () -> 
wrapper.loadTableMetadataFromLocation(location));
+      Assertions.assertTrue(
+          e.getMessage().contains("unsupported or unreadable scheme"), 
e.getMessage());
+      Assertions.assertFalse(e.getMessage().contains("No FileSystem"), 
e.getMessage());
+    }
+  }
+
   @ParameterizedTest
   @ValueSource(booleans = {true, false})
   void testPurgeDeletesWhatCanBeReadWhenAManifestListIsMissing(
diff --git 
a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/CatalogWrapperForREST.java
 
b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/CatalogWrapperForREST.java
index d96c2f9cba..3ef5d18e11 100644
--- 
a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/CatalogWrapperForREST.java
+++ 
b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/CatalogWrapperForREST.java
@@ -24,6 +24,7 @@ import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.ImmutableSet;
 import java.io.IOException;
 import java.net.URI;
+import java.time.format.DateTimeParseException;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.HashMap;
@@ -550,9 +551,11 @@ public class CatalogWrapperForREST extends 
IcebergCatalogWrapper {
       scanPlanCache.put(ScanPlanCacheKey.create(tableIdentifier, table, 
scanRequest), response);
       return response;
 
-    } catch (IllegalArgumentException | ValidationException e) {
-      // A filter is bound to the schema only while files are planned, so an 
unknown column or a
-      // value of the wrong type surfaces here as a ValidationException.
+    } catch (IllegalArgumentException | ValidationException | 
DateTimeParseException e) {
+      // A filter is bound to the schema only while files are planned. Unknown 
columns and wrong
+      // literal types usually surface as ValidationException; a timestamp 
without a zone compared
+      // to timestamptz surfaces as DateTimeParseException. Broader 
DateTimeException is not
+      // caught so unrelated server-side date/time bugs stay 5xx.
       LOG.info("Invalid scan request for table {}: {}", tableIdentifier, 
e.getMessage());
       throw new IllegalArgumentException(
           "Invalid scan parameters: " + withoutSchemaStruct(e.getMessage()), 
e);
diff --git 
a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/IcebergExceptionMapper.java
 
b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/IcebergExceptionMapper.java
index de60c69dcc..d4d4b09839 100644
--- 
a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/IcebergExceptionMapper.java
+++ 
b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/IcebergExceptionMapper.java
@@ -74,7 +74,12 @@ public class IcebergExceptionMapper implements 
ExceptionMapper<Throwable> {
           .put(TokenExpiredException.class, 419)
           .put(org.apache.gravitino.exceptions.ForbiddenException.class, 403)
           .put(ForbiddenException.class, 403)
+          // javax.ws.rs.NotFoundException (JAX-RS, imported above) for an 
unknown REST path.
           .put(NotFoundException.class, 404)
+          // Iceberg NotFoundException is intentionally unmapped (defaults to 
500). It can mean a
+          // server-side missing file (table metadata/manifest gone from 
storage), not only a bad
+          // client path. Request-supplied metadata-location cases convert to 
BadRequestException at
+          // the call site (e.g. loadTableMetadataFromLocation / registerTable 
/ registerView).
           .put(NoSuchNamespaceException.class, 404)
           .put(NoSuchTableException.class, 404)
           .put(NoSuchIcebergTableException.class, 404)
diff --git 
a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/RegisterTableAuthzHandler.java
 
b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/RegisterTableAuthzHandler.java
index 209cbf5776..0ab300d010 100644
--- 
a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/RegisterTableAuthzHandler.java
+++ 
b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/server/web/filter/RegisterTableAuthzHandler.java
@@ -43,6 +43,7 @@ import org.apache.gravitino.utils.PrincipalUtils;
 import org.apache.iceberg.TableMetadata;
 import org.apache.iceberg.catalog.Namespace;
 import org.apache.iceberg.catalog.TableIdentifier;
+import org.apache.iceberg.exceptions.BadRequestException;
 import org.apache.iceberg.rest.requests.RegisterTableRequest;
 
 /**
@@ -85,11 +86,18 @@ public class RegisterTableAuthzHandler implements 
AuthorizationHandler {
     this.parameters = parameters;
     this.args = args;
     RegisterTableRequest request = registerTableRequest();
-    this.accessEntityType = request.overwrite() ? EntityType.TABLE : 
EntityType.SCHEMA;
+    // A missing body is validated in process(); default to SCHEMA so 
entityType() is defined.
+    this.accessEntityType =
+        request != null && request.overwrite() ? EntityType.TABLE : 
EntityType.SCHEMA;
     NameIdentifier metalakeIdent = nameIdentifierMap.get(EntityType.METALAKE);
     NameIdentifier catalogIdent = nameIdentifierMap.get(EntityType.CATALOG);
     NameIdentifier schemaIdent = nameIdentifierMap.get(EntityType.SCHEMA);
-    if (metalakeIdent != null && catalogIdent != null && schemaIdent != null) {
+    if (request != null
+        && request.name() != null
+        && !request.name().isEmpty()
+        && metalakeIdent != null
+        && catalogIdent != null
+        && schemaIdent != null) {
       nameIdentifierMap.put(
           EntityType.TABLE,
           NameIdentifierUtil.ofTable(
@@ -100,6 +108,12 @@ public class RegisterTableAuthzHandler implements 
AuthorizationHandler {
   @Override
   public void process(Map<EntityType, NameIdentifier> nameIdentifierMap) {
     RegisterTableRequest request = registerTableRequest();
+    if (request == null) {
+      throw new BadRequestException("Invalid request: a RegisterTableRequest 
body is required");
+    }
+    if (request.name() == null || request.name().isEmpty()) {
+      throw new BadRequestException("Invalid request: table name is required");
+    }
 
     NameIdentifier metalakeIdent = nameIdentifierMap.get(EntityType.METALAKE);
     NameIdentifier catalogIdent = nameIdentifierMap.get(EntityType.CATALOG);
diff --git 
a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/TestIcebergExceptionMapper.java
 
b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/TestIcebergExceptionMapper.java
index 1c88bd5220..cd1e548a1c 100644
--- 
a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/TestIcebergExceptionMapper.java
+++ 
b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/TestIcebergExceptionMapper.java
@@ -77,6 +77,32 @@ public class TestIcebergExceptionMapper {
     checkExceptionStatus(new CommitStateUnknownException("", new 
RuntimeException()), 500);
     checkExceptionStatus(new ServiceUnavailableException(""), 503);
     checkExceptionStatus(new RuntimeException(), 500);
+    // Iceberg NotFoundException stays unmapped → 500. Client-supplied 
metadata-location misses are
+    // converted to BadRequestException at the call site, not here.
+    checkExceptionStatus(new 
org.apache.iceberg.exceptions.NotFoundException(""), 500);
+    checkExceptionStatus(new BadRequestException(""), 400);
+  }
+
+  @Test
+  public void 
testRequestSuppliedMetadataLocationMissesAreBadRequestNotMapperNotFound() {
+    // Unconverted Iceberg NotFoundException would be 500 (mapper 
intentionally omits it).
+    checkExceptionStatus(
+        new org.apache.iceberg.exceptions.NotFoundException("Failed to open 
input stream"), 500);
+    // registerTable / registerView / loadTableMetadataFromLocation convert 
first; those messages
+    // must map to 400. Call-site conversion is covered in 
TestIcebergCatalogWrapper.
+    checkExceptionStatus(
+        new BadRequestException(
+            "Cannot register table ghost: metadata location 
file:/missing/v1.metadata.json does not"
+                + " exist"),
+        400);
+    checkExceptionStatus(
+        new BadRequestException(
+            "Cannot register view ghost: metadata location 
file:/missing/v1.metadata.json does not"
+                + " exist"),
+        400);
+    checkExceptionStatus(
+        new BadRequestException("Metadata location 
file:/missing/v1.metadata.json does not exist"),
+        400);
   }
 
   @Test
diff --git 
a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/TestIcebergScanPlanning.java
 
b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/TestIcebergScanPlanning.java
index 4f0d1d034f..d0e865e45a 100644
--- 
a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/TestIcebergScanPlanning.java
+++ 
b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/TestIcebergScanPlanning.java
@@ -123,6 +123,48 @@ public class TestIcebergScanPlanning {
         unknownStats.getMessage().contains("NullPointerException"), 
unknownStats.getMessage());
   }
 
+  @Test
+  public void testTimestamptzFilterWithoutZoneIsClientError() {
+    // #14421: binding a zone-less timestamp literal to timestamptz throws 
DateTimeParseException
+    // only while files are planned (empty tables return 200, matching 
Iceberg).
+    TableIdentifier ident = TableIdentifier.of(Namespace.of("db"), "tstz");
+    Table tstz =
+        wrapper
+            .getCatalog()
+            .createTable(
+                ident,
+                new Schema(
+                    Types.NestedField.required(1, "id", Types.LongType.get()),
+                    Types.NestedField.optional(2, "c_tstz", 
Types.TimestampType.withZone())),
+                PartitionSpec.unpartitioned());
+    tstz.newFastAppend()
+        .appendFile(
+            DataFiles.builder(PartitionSpec.unpartitioned())
+                .withPath("/data/tstz.parquet")
+                .withFileSizeInBytes(10)
+                .withRecordCount(1)
+                .build())
+        .commit();
+
+    IllegalArgumentException withoutZone =
+        Assertions.assertThrows(
+            IllegalArgumentException.class,
+            () ->
+                planFiles(
+                    ident,
+                    PlanTableScanRequest.builder()
+                        .withFilter(Expressions.equal("c_tstz", 
"2024-06-01T12:00:00"))));
+    Assertions.assertTrue(
+        withoutZone.getMessage().contains("Invalid scan parameters"), 
withoutZone.getMessage());
+
+    Assertions.assertDoesNotThrow(
+        () ->
+            planFiles(
+                ident,
+                PlanTableScanRequest.builder()
+                    .withFilter(Expressions.equal("c_tstz", 
"2024-06-01T12:00:00+00:00"))));
+  }
+
   @Test
   public void testConstantFiltersInTheSpecFormAreAccepted() throws Exception {
     PlanTableScanRequest request =
diff --git 
a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergNamespaceOperationExecutor.java
 
b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergNamespaceOperationExecutor.java
index d050d96828..ec74c4ea66 100644
--- 
a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergNamespaceOperationExecutor.java
+++ 
b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/iceberg/service/dispatcher/TestIcebergNamespaceOperationExecutor.java
@@ -213,6 +213,27 @@ public class TestIcebergNamespaceOperationExecutor {
     verifyNoInteractions(mockCatalogWrapper);
   }
 
+  @Test
+  public void testRegisterTablePropagatesMissingMetadataLocationBadRequest() {
+    Namespace namespace = Namespace.of("test_namespace");
+    String metadataLocation = "file:/tmp/missing/v1.metadata.json";
+    RegisterTableRequest request = mock(RegisterTableRequest.class);
+    when(request.name()).thenReturn("ghost");
+    when(request.metadataLocation()).thenReturn(metadataLocation);
+    when(mockCatalogWrapper.loadTableMetadataFromLocation(metadataLocation))
+        .thenThrow(
+            new BadRequestException("Metadata location %s does not exist", 
metadataLocation));
+
+    BadRequestException thrown =
+        Assertions.assertThrows(
+            BadRequestException.class,
+            () -> executor.registerTable(mockContext, namespace, request));
+
+    Assertions.assertTrue(thrown.getMessage().contains("does not exist"), 
thrown.getMessage());
+    verify(mockCatalogWrapper).loadTableMetadataFromLocation(metadataLocation);
+    verify(mockCatalogWrapper, never()).registerTable(any(), any(), 
any(Boolean.class));
+  }
+
   @ParameterizedTest
   @ValueSource(
       ints = {EntityFieldLimits.MAX_NAME_LENGTH + 1, 
EntityFieldLimits.MAX_COLUMN_NAME_LENGTH})
diff --git 
a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/server/web/filter/TestRegisterTableAuthzHandler.java
 
b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/server/web/filter/TestRegisterTableAuthzHandler.java
index f30ced7450..0681e21562 100644
--- 
a/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/server/web/filter/TestRegisterTableAuthzHandler.java
+++ 
b/iceberg/iceberg-rest-server/src/test/java/org/apache/gravitino/server/web/filter/TestRegisterTableAuthzHandler.java
@@ -252,17 +252,62 @@ class TestRegisterTableAuthzHandler {
     verify(invocation, never()).proceed();
   }
 
+  @Test
+  void testMissingRequestBodyIsBadRequest() throws Throwable {
+    allow(Privilege.Name.USE_CATALOG, Privilege.Name.USE_SCHEMA, 
Privilege.Name.CREATE_TABLE);
+
+    MethodInvocation invocation = registerInvocationWithRequest(null);
+    Object result = interceptor.invoke(invocation);
+    assertBadRequest(result);
+    verify(invocation, never()).proceed();
+  }
+
+  @Test
+  void testMissingTableNameIsBadRequest() throws Throwable {
+    allow(Privilege.Name.USE_CATALOG, Privilege.Name.USE_SCHEMA, 
Privilege.Name.CREATE_TABLE);
+
+    RegisterTableRequest nullName = mock(RegisterTableRequest.class);
+    when(nullName.name()).thenReturn(null);
+    when(nullName.metadataLocation()).thenReturn(META_LOC);
+    MethodInvocation nullNameInvocation = 
registerInvocationWithRequest(nullName);
+    assertBadRequest(interceptor.invoke(nullNameInvocation));
+    verify(nullNameInvocation, never()).proceed();
+
+    MethodInvocation emptyNameInvocation = registerInvocation(false, "", 
META_LOC);
+    assertBadRequest(interceptor.invoke(emptyNameInvocation));
+    verify(emptyNameInvocation, never()).proceed();
+  }
+
+  @Test
+  void testUnreadableMetadataLocationIsBadRequestNotAuthzInternalError() 
throws Throwable {
+    allow(Privilege.Name.USE_CATALOG, Privilege.Name.USE_SCHEMA, 
Privilege.Name.CREATE_TABLE);
+    when(catalogWrapper.loadTableMetadataFromLocation(any()))
+        .thenThrow(
+            new org.apache.iceberg.exceptions.BadRequestException(
+                "Metadata location %s is not a valid metadata file: 
directory", META_LOC));
+
+    MethodInvocation invocation = registerInvocation(false, TABLE, META_LOC);
+    Object result = interceptor.invoke(invocation);
+    assertBadRequest(result);
+    verify(invocation, never()).proceed();
+  }
+
   private MethodInvocation registerInvocation(
       boolean overwrite, String tableName, String metadataLocation) throws 
Throwable {
-    Method method =
-        IcebergNamespaceOperations.class.getMethod(
-            "registerTable", String.class, String.class, 
RegisterTableRequest.class, String.class);
     RegisterTableRequest request =
         ImmutableRegisterTableRequest.builder()
             .name(tableName)
             .metadataLocation(metadataLocation)
             .overwrite(overwrite)
             .build();
+    return registerInvocationWithRequest(request);
+  }
+
+  private MethodInvocation registerInvocationWithRequest(RegisterTableRequest 
request)
+      throws Throwable {
+    Method method =
+        IcebergNamespaceOperations.class.getMethod(
+            "registerTable", String.class, String.class, 
RegisterTableRequest.class, String.class);
     MethodInvocation invocation = mock(MethodInvocation.class);
     when(invocation.getMethod()).thenReturn(method);
     when(invocation.getArguments()).thenReturn(new Object[] {CATALOG + "/", 
SCHEMA, request, null});
@@ -335,4 +380,10 @@ class TestRegisterTableAuthzHandler {
     assertEquals(Response.Status.FORBIDDEN.getStatusCode(), 
response.getStatus());
     assertInstanceOf(ErrorResponse.class, response.getEntity());
   }
+
+  private static void assertBadRequest(Object result) {
+    Response response = assertInstanceOf(Response.class, result);
+    assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), 
response.getStatus());
+    assertInstanceOf(ErrorResponse.class, response.getEntity());
+  }
 }

Reply via email to