~jan0sch/smederee

Showing details for patch ceb670bd04b2fa6652466a94acf291e88c6dcdd5.
2024-02-06 (Tue), 4:09 PM - Jens Grassel - ceb670bd04b2fa6652466a94acf291e88c6dcdd5

Hub: Add error handling middleware for better error logging.

Summary of changes
1 files modified with 19 lines added and 1 lines removed
  • modules/hub/src/main/scala/de/smederee/hub/HubServer.scala with 19 added and 1 removed lines
diff -rN -u old-smederee/modules/hub/src/main/scala/de/smederee/hub/HubServer.scala new-smederee/modules/hub/src/main/scala/de/smederee/hub/HubServer.scala
--- old-smederee/modules/hub/src/main/scala/de/smederee/hub/HubServer.scala	2025-01-13 01:26:57.437797542 +0000
+++ new-smederee/modules/hub/src/main/scala/de/smederee/hub/HubServer.scala	2025-01-13 01:26:57.437797542 +0000
@@ -42,6 +42,8 @@
 import org.http4s.implicits.*
 import org.http4s.server.*
 import org.http4s.server.middleware.CSRF
+import org.http4s.server.middleware.ErrorAction
+import org.http4s.server.middleware.ErrorHandling
 import org.http4s.server.staticcontent.resourceServiceBuilder
 import org.slf4j.LoggerFactory
 import pureconfig.*
@@ -127,6 +129,15 @@
         }
     }
 
+    /** An error handler that simply logs error messages but nothing more.
+      *
+      * @param exception
+      *   An exception thrown by underlying code.
+      * @param message
+      *   An error message.
+      */
+    private def handleError(exception: Throwable, message: => String) = IO(log.error(message, exception))
+
     /** Try to load the CSRF key from the given path. If it doesn't exist or fails then a new key is generated and
       * stored in the file.
       *
@@ -545,12 +556,19 @@
                                 )
                         )
                     )
+                    errorHandlingMiddleware = ErrorHandling.Recover.total(
+                        ErrorAction.log(
+                            hubWebService,
+                            messageFailureLogAction = handleError,
+                            serviceErrorLogAction = handleError
+                        )
+                    )
                     // Create our webserver fiber.
                     resource = EmberServerBuilder
                         .default[IO]
                         .withHost(hubConfiguration.service.host)
                         .withPort(hubConfiguration.service.port)
-                        .withHttpApp(csrfMiddleware.validate()(hubWebService))
+                        .withHttpApp(csrfMiddleware.validate()(errorHandlingMiddleware))
                         .build
                     webServer = resource.use(server =>
                         IO(log.info("Server started at {}", server.address)) >> IO.never.as(ExitCode.Success)