Merge branch 'main' into combined-prs-branch
[e-mobility-charging-stations-simulator.git] / src / charging-station / ui-server / UIHttpServer.ts
index 27e8d7ba9051654d777f904b7e5ff16c884b0a47..fb967ef4ecb0403d54b074738e11dcfb8446af05 100644 (file)
@@ -3,7 +3,7 @@ import type { IncomingMessage, ServerResponse } from 'node:http'
 import { StatusCodes } from 'http-status-codes'
 
 import { AbstractUIServer } from './AbstractUIServer.js'
-import { UIServerUtils } from './UIServerUtils.js'
+import { isProtocolAndVersionSupported } from './UIServerUtils.js'
 import { BaseError } from '../../exception/index.js'
 import {
   ApplicationProtocolVersion,
@@ -95,7 +95,7 @@ export class UIHttpServer extends AbstractUIServer {
             'WWW-Authenticate': 'Basic realm=users'
           })
           .end(`${StatusCodes.UNAUTHORIZED} Unauthorized`)
-          .destroy()
+        res.destroy()
         req.destroy()
       }
     })
@@ -109,7 +109,7 @@ export class UIHttpServer extends AbstractUIServer {
     this.responseHandlers.set(uuid, res)
     try {
       const fullProtocol = `${protocol}${version}`
-      if (!UIServerUtils.isProtocolAndVersionSupported(fullProtocol)) {
+      if (!isProtocolAndVersionSupported(fullProtocol)) {
         throw new BaseError(`Unsupported UI protocol version: '${fullProtocol}'`)
       }
       this.registerProtocolVersionUIService(version)
@@ -126,10 +126,22 @@ export class UIHttpServer extends AbstractUIServer {
             bodyBuffer.push(chunk)
           })
           .on('end', () => {
-            const body = JSON.parse(Buffer.concat(bodyBuffer).toString()) as RequestPayload
+            let requestPayload: RequestPayload | undefined
+            try {
+              requestPayload = JSON.parse(Buffer.concat(bodyBuffer).toString()) as RequestPayload
+            } catch (error) {
+              this.sendResponse(
+                this.buildProtocolResponse(uuid, {
+                  status: ResponseStatus.FAILURE,
+                  errorMessage: (error as Error).message,
+                  errorStack: (error as Error).stack
+                })
+              )
+              return
+            }
             this.uiServices
               .get(version)
-              ?.requestHandler(this.buildProtocolRequest(uuid, procedureName, body))
+              ?.requestHandler(this.buildProtocolRequest(uuid, procedureName, requestPayload))
               .then((protocolResponse?: ProtocolResponse) => {
                 if (protocolResponse != null) {
                   this.sendResponse(protocolResponse)