Refined error handling

This commit is contained in:
Benjamin Höglinger-Stelzer 2024-07-13 17:20:18 +02:00
parent 3231f4822f
commit 582412f4dc
2 changed files with 18 additions and 3 deletions

View File

@ -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;
}
/// <summary>
/// The Win32 error that caused the exception.
/// </summary>
public int Win32Error { get; } = Marshal.GetLastWin32Error();
}

View File

@ -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;