From 846c8e13af5167f2061c662a391fa44017b1a54f Mon Sep 17 00:00:00 2001
From: Tomas Cohen Arazi <tomascohen@theke.io>
Date: Mon, 20 Jan 2025 10:06:22 -0300
Subject: [PATCH] Bug 38926: Make POST /biblios return 400 if AddBiblio fails

We don't have proper exceptions in the `C4::Biblio::AddBiblio` method,
but we at least know `$biblio_id` will be `undef` in the even of an
error processing the call.

This patch makes the controller handle this situation so (at least) it
is obvious that something bad happened.

To test:
1. Apply the regression tests patch
2. Run:
   $ ktd --shell
  k$ prove t/db_dependent/api/v1/biblios.t
=> FAIL: Tests fail! The endpoint returns 200 even on error!
3. Apply this patch
4. Repeat 2
=> SUCCESS: Tests pass! The endpoint returns a 400 with a reasonable
message!
5. Sign off :-D

Signed-off-by: Jonathan Druart <jonathan.druart@bugs.koha-community.org>
Signed-off-by: David Nind <david@davidnind.com>
---
 Koha/REST/V1/Biblios.pm           | 17 +++++++++++++++--
 api/v1/swagger/paths/biblios.yaml |  5 ++++-
 2 files changed, 19 insertions(+), 3 deletions(-)

diff --git a/Koha/REST/V1/Biblios.pm b/Koha/REST/V1/Biblios.pm
index 035d215c52..010f96e7e9 100644
--- a/Koha/REST/V1/Biblios.pm
+++ b/Koha/REST/V1/Biblios.pm
@@ -703,9 +703,22 @@ sub add {
             }
         ) unless !$duplicatebiblionumber || $confirm_not_duplicate;
 
-        my ( $biblio_id ) = AddBiblio( $record, $frameworkcode, { record_source_id => $record_source_id } );
+        my ($biblio_id) = C4::Biblio::AddBiblio( $record, $frameworkcode, { record_source_id => $record_source_id } );
 
-        $c->render(
+        if ( !$biblio_id ) {
+
+            # FIXME: AddBiblio wraps everything inside a transaction and a try/catch block
+            # this will need a tweak if this behavior changes
+            return $c->render(
+                status  => 400,
+                openapi => {
+                    error      => 'Error creating record',
+                    error_code => 'record_creation_failed',
+                },
+            );
+        }
+
+        return $c->render(
             status  => 200,
             openapi => { id => $biblio_id }
         );
diff --git a/api/v1/swagger/paths/biblios.yaml b/api/v1/swagger/paths/biblios.yaml
index 6502a4f67d..89252ce9f1 100644
--- a/api/v1/swagger/paths/biblios.yaml
+++ b/api/v1/swagger/paths/biblios.yaml
@@ -29,7 +29,10 @@
       "200":
         description: A biblio
       "400":
-        description: Bad request
+        description: |
+          Bad request. Possible `error_code` attribute values:
+
+            * `record_creation_failed`: An error occurred during record creation. The cause could not be determined.
         schema:
           $ref: "../swagger.yaml#/definitions/error"
       "401":
-- 
2.39.5