From 582412f4dc0e2e455473ade96570f521b9999194 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20H=C3=B6glinger-Stelzer?= Date: Sat, 13 Jul 2024 17:20:18 +0200 Subject: [PATCH] Refined error handling --- Nefarius.Peripherals.SerialPort/CommPortException.cs | 11 +++++++++++ Nefarius.Peripherals.SerialPort/SerialPort.cs | 10 +++++++--- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/Nefarius.Peripherals.SerialPort/CommPortException.cs b/Nefarius.Peripherals.SerialPort/CommPortException.cs index bb4c8e7..7be3875 100644 --- a/Nefarius.Peripherals.SerialPort/CommPortException.cs +++ b/Nefarius.Peripherals.SerialPort/CommPortException.cs @@ -1,4 +1,5 @@ using System; +using System.Runtime.InteropServices; namespace Nefarius.Peripherals.SerialPort; @@ -22,4 +23,14 @@ public class CommPortException : ApplicationException public CommPortException(Exception e) : base("Receive Thread Exception", e) { } + + public CommPortException(string message, int error) : base(message) + { + Win32Error = error; + } + + /// + /// The Win32 error that caused the exception. + /// + public int Win32Error { get; } = Marshal.GetLastWin32Error(); } \ No newline at end of file diff --git a/Nefarius.Peripherals.SerialPort/SerialPort.cs b/Nefarius.Peripherals.SerialPort/SerialPort.cs index c51177f..3293f2e 100644 --- a/Nefarius.Peripherals.SerialPort/SerialPort.cs +++ b/Nefarius.Peripherals.SerialPort/SerialPort.cs @@ -70,8 +70,12 @@ public partial class SerialPort : IDisposable } _hPort = PInvoke.CreateFile(PortName, - (uint)(FILE_ACCESS_RIGHTS.FILE_GENERIC_READ | FILE_ACCESS_RIGHTS.FILE_GENERIC_WRITE), 0, - null, FILE_CREATION_DISPOSITION.OPEN_EXISTING, FILE_FLAGS_AND_ATTRIBUTES.FILE_FLAG_OVERLAPPED, null); + (uint)(FILE_ACCESS_RIGHTS.FILE_GENERIC_READ | FILE_ACCESS_RIGHTS.FILE_GENERIC_WRITE), + 0, + null, + FILE_CREATION_DISPOSITION.OPEN_EXISTING, FILE_FLAGS_AND_ATTRIBUTES.FILE_FLAG_OVERLAPPED, + null + ); if (_hPort.IsInvalid) { @@ -80,7 +84,7 @@ public partial class SerialPort : IDisposable return false; } - throw new CommPortException("Port Open Failure"); + throw new CommPortException("Port Open Failure", Marshal.GetLastWin32Error()); } _online = true;