refactor: improve error reporting in the UI server code
authorJérôme Benoit <jerome.benoit@sap.com>
Thu, 22 Feb 2024 09:34:11 +0000 (10:34 +0100)
committerJérôme Benoit <jerome.benoit@sap.com>
Thu, 22 Feb 2024 09:34:11 +0000 (10:34 +0100)
Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
src/charging-station/ui-server/AbstractUIServer.ts
src/charging-station/ui-server/UIWebSocketServer.ts

index 61593db54b1e233cda4b489c39a4d937c518a71f..566d496167d288d0861ad694cd81ee19c61b90f6 100644 (file)
@@ -19,6 +19,9 @@ import {
   type ResponsePayload,
   type UIServerConfiguration
 } from '../../types/index.js'
+import { logger } from '../../utils/index.js'
+
+const moduleName = 'AbstractUIServer'
 
 export abstract class AbstractUIServer {
   public readonly chargingStations: Map<string, ChargingStationData>
@@ -84,6 +87,12 @@ export abstract class AbstractUIServer {
   }
 
   protected startHttpServer (): void {
+    this.httpServer.on('error', error => {
+      logger.error(
+        `${this.logPrefix(moduleName, 'start.httpServer.on.error')} HTTP server error:`,
+        error
+      )
+    })
     if (!this.httpServer.listening) {
       this.httpServer.listen(this.uiServerConfiguration.options)
     }
@@ -116,6 +125,7 @@ export abstract class AbstractUIServer {
   private stopHttpServer (): void {
     if (this.httpServer.listening) {
       this.httpServer.close()
+      this.httpServer.removeAllListeners()
     }
   }
 
index 368a09fe90d4f5522a593133a31e679a109ff23a..1e1a372c698a941365df864aac280aa3bb32778c 100644 (file)
@@ -91,6 +91,16 @@ export class UIWebSocketServer extends AbstractUIServer {
       }
     })
     this.httpServer.on('upgrade', (req: IncomingMessage, socket: Duplex, head: Buffer): void => {
+      const onSocketError = (error: Error): void => {
+        logger.error(
+          `${this.logPrefix(
+            moduleName,
+            'start.httpServer.on.upgrade'
+          )} Socket error at connection upgrade event handling:`,
+          error
+        )
+      }
+      socket.on('error', onSocketError)
       this.authenticate(req, err => {
         if (err != null) {
           socket.write(`HTTP/1.1 ${StatusCodes.UNAUTHORIZED} Unauthorized\r\n\r\n`)
@@ -106,11 +116,12 @@ export class UIWebSocketServer extends AbstractUIServer {
             `${this.logPrefix(
               moduleName,
               'start.httpServer.on.upgrade'
-            )} Error at handling connection upgrade:`,
+            )} Error at connection upgrade event handling:`,
             error
           )
         }
       })
+      socket.removeListener('error', onSocketError)
     })
     this.startHttpServer()
   }