From cb22cf521a550bb098ffa611cb2f13c5286f7c36 Mon Sep 17 00:00:00 2001 From: Gerrit Edzards Date: Tue, 17 Sep 2024 13:52:27 +0200 Subject: [PATCH] Improve exception handling --- .../Misc/VirtualTcpInputPrinter.cs | 59 ++++++++++++------- 1 file changed, 37 insertions(+), 22 deletions(-) diff --git a/Common/AmagnoVirtualPrinter.Agent.Lib/Misc/VirtualTcpInputPrinter.cs b/Common/AmagnoVirtualPrinter.Agent.Lib/Misc/VirtualTcpInputPrinter.cs index b1a6ca1..9075b86 100644 --- a/Common/AmagnoVirtualPrinter.Agent.Lib/Misc/VirtualTcpInputPrinter.cs +++ b/Common/AmagnoVirtualPrinter.Agent.Lib/Misc/VirtualTcpInputPrinter.cs @@ -92,41 +92,56 @@ private void StartFileWatcher([NotNull] string dir) private void HandleClient([NotNull]IAsyncResult ar) { - const string printer = Defaults.PrinterName; - IJob job; - - var socket = (TcpListener) ar.AsyncState; - using (var client = socket.EndAcceptTcpClient(ar)) + try { - var local = client.Client.LocalEndPoint; - var remote = client.Client.RemoteEndPoint; + const string printer = Defaults.PrinterName; + IJob job; - LogDebug($"{remote} --> {local}"); - job = _jobFactory.Create(printer, client.GetStream()); - } + var socket = (TcpListener) ar.AsyncState; + using (var client = socket.EndAcceptTcpClient(ar)) + { + var local = client.Client.LocalEndPoint; + var remote = client.Client.RemoteEndPoint; + + LogDebug($"{remote} --> {local}"); + job = _jobFactory.Create(printer, client.GetStream()); + } - socket.BeginAcceptTcpClient(HandleClient, ar.AsyncState); + socket.BeginAcceptTcpClient(HandleClient, ar.AsyncState); - if (job == null) - { - LogError("Job could not be created. Check your Printer Settings."); + if (job == null) + { + LogError("Job could not be created. Check your Printer Settings."); + } + else + { + LogDebug($"Temporarily printed '{job.RawDataPath}'!"); + _jobService.Start(job); + RestartFileWatcherIfNeeded(job.SessionInfo.Sid); + } } - else + catch (Exception e) { - LogDebug($"Temporarily printed '{job.RawDataPath}'!"); - _jobService.Start(job); - RestartFileWatcherIfNeeded(job.SessionInfo.Sid); + LogError($"Exception thrown in {nameof(HandleClient)}", e); + throw; } } private void RestartFileWatcherIfNeeded(string sid) { - var config = GetUserRegistryConfig(sid); - _outputDir = _directoryHelper.GetOutputDirectory(config); + try + { + var config = GetUserRegistryConfig(sid); + _outputDir = _directoryHelper.GetOutputDirectory(config); - if (_watcher == null || _watcher.Path != _outputDir) + if (_watcher == null || _watcher.Path != _outputDir) + { + StartFileWatcher(_outputDir); + } + } + catch (Exception e) { - StartFileWatcher(_outputDir); + LogError($"Thrown exception in {nameof(RestartFileWatcherIfNeeded)}", e); } }