From 426bc6269c28d9adef170d2b035f8f4c3f3ff4ab Mon Sep 17 00:00:00 2001
From: Nelson Kopliku <nelson.kopliku@suse.com>
Date: Wed, 2 Jul 2025 13:59:26 +0200
Subject: [PATCH 1/3] Catch discovery exceptions

---
 lib/trento/discovery.ex                           | 5 +++++
 lib/trento_web/controllers/fallback_controller.ex | 7 +++++++
 2 files changed, 12 insertions(+)

diff --git a/lib/trento/discovery.ex b/lib/trento/discovery.ex
index f6c416818d..e481c29b82 100644
--- a/lib/trento/discovery.ex
+++ b/lib/trento/discovery.ex
@@ -42,6 +42,11 @@ defmodule Trento.Discovery do
 
         error
     end
+  rescue
+    error ->
+      IO.inspect(error, label: "Error handling discovery event")
+      store_discarded_discovery_event(event, inspect(error))
+      {:error, :discovery_exception}
   end
 
   @doc """
diff --git a/lib/trento_web/controllers/fallback_controller.ex b/lib/trento_web/controllers/fallback_controller.ex
index a828e4174a..b3c649bcff 100644
--- a/lib/trento_web/controllers/fallback_controller.ex
+++ b/lib/trento_web/controllers/fallback_controller.ex
@@ -95,6 +95,13 @@ defmodule TrentoWeb.FallbackController do
     |> render(:"422", reason: "Unknown discovery type.")
   end
 
+  def call(conn, {:error, :discovery_exception}) do
+    conn
+    |> put_status(:unprocessable_entity)
+    |> put_view(json: ErrorJSON)
+    |> render(:"422", reason: "Unable to handle discovery.")
+  end
+
   def call(conn, {:error, :host_alive}) do
     conn
     |> put_status(:unprocessable_entity)

From 132e0ae66f4b1b47ca7433a58db8ead6b6dd129a Mon Sep 17 00:00:00 2001
From: Kristiyan Kanchev <kristiyan.kanchev@suse.com>
Date: Wed, 2 Jul 2025 17:37:11 +0300
Subject: [PATCH 2/3] Added test for unexpectedly failed discovery event

---
 lib/trento/discovery.ex        |  2 +-
 test/trento/discovery_test.exs | 22 ++++++++++++++++++++++
 2 files changed, 23 insertions(+), 1 deletion(-)

diff --git a/lib/trento/discovery.ex b/lib/trento/discovery.ex
index e481c29b82..686b7a848f 100644
--- a/lib/trento/discovery.ex
+++ b/lib/trento/discovery.ex
@@ -44,7 +44,7 @@ defmodule Trento.Discovery do
     end
   rescue
     error ->
-      IO.inspect(error, label: "Error handling discovery event")
+      Logger.error("Error handling discovery event: #{inspect(error)}")
       store_discarded_discovery_event(event, inspect(error))
       {:error, :discovery_exception}
   end
diff --git a/test/trento/discovery_test.exs b/test/trento/discovery_test.exs
index 02c603a4bc..ede7a75996 100644
--- a/test/trento/discovery_test.exs
+++ b/test/trento/discovery_test.exs
@@ -13,6 +13,8 @@ defmodule Trento.DiscoveryTest do
     DiscoveryEvent
   }
 
+  setup :verify_on_exit!
+
   test "should retrieve the current set of discovery events" do
     agent_id_1 = Faker.UUID.v4()
     agent_id_2 = Faker.UUID.v4()
@@ -144,4 +146,24 @@ defmodule Trento.DiscoveryTest do
     assert %DiscardedDiscoveryEvent{payload: ^event} =
              discarded_event
   end
+
+  test "should discard discovery events when the dispatch action fails unexpectedly" do
+    event = %{
+      "agent_id" => Faker.UUID.v4(),
+      "discovery_type" => "host_discovery",
+      "payload" => build(:host_discovery_event)
+    }
+
+    expect(Trento.Commanded.Mock, :dispatch, fn _ ->
+      raise "Test Exception"
+    end)
+
+    {:error, error} = Discovery.handle(event)
+    [discarded_event] = Trento.Repo.all(DiscardedDiscoveryEvent)
+
+    assert :discovery_exception === error
+
+    assert %DiscardedDiscoveryEvent{payload: ^event} =
+             discarded_event
+  end
 end

From 962638317d05cca413b6058caea6865440477079 Mon Sep 17 00:00:00 2001
From: Kristiyan Kanchev <kristiyan.kanchev@suse.com>
Date: Wed, 2 Jul 2025 17:54:53 +0300
Subject: [PATCH 3/3] Added test for discovery controller: 422 when unexpected
 error

---
 .../v1/discovery_controller_test.exs          | 25 +++++++++++++++++++
 1 file changed, 25 insertions(+)

diff --git a/test/trento_web/controllers/v1/discovery_controller_test.exs b/test/trento_web/controllers/v1/discovery_controller_test.exs
index 3207cfd7cd..87e7198f9f 100644
--- a/test/trento_web/controllers/v1/discovery_controller_test.exs
+++ b/test/trento_web/controllers/v1/discovery_controller_test.exs
@@ -84,5 +84,30 @@ defmodule TrentoWeb.V1.DiscoveryControllerTest do
       assert %DiscardedDiscoveryEvent{payload: ^body, reason: "[:associated_database_not_found]"} =
                discarded_event
     end
+
+    test "collect action returns error when unexpected error has happened during event processing",
+         %{conn: conn} do
+      body =
+        load_discovery_event_fixture("sap_system_discovery_application")
+
+      expect(Trento.Commanded.Mock, :dispatch, fn _ ->
+        raise "Test Exception"
+      end)
+
+      %{status: status} =
+        conn
+        |> put_req_header("content-type", "application/json")
+        |> post("/api/v1/collect", body)
+
+      assert status == 422
+
+      [discarded_event] = Discovery.get_discarded_discovery_events(1)
+
+      assert %DiscardedDiscoveryEvent{
+               payload: ^body,
+               reason: "%RuntimeError{message: \"Test Exception\"}"
+             } =
+               discarded_event
+    end
   end
 end
