using System; using System.Runtime.InteropServices; using System.Runtime.Serialization; using AMWD.Protocols.Modbus.Serial.Utils; #if NETSTANDARD using System.Security.Permissions; #endif namespace AMWD.Protocols.Modbus.Serial { /// /// Represents a unix specific IO exception. /// /// /// See StackOverflow answer: . /// [Serializable] [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] public class UnixIOException : ExternalException { /// /// Initializes a new instance of the class. /// #if NETSTANDARD [SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)] #endif public UnixIOException() : this(Marshal.GetLastWin32Error()) { } /// /// Initializes a new instance of the class. /// /// The native error code. #if NETSTANDARD [SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)] #endif public UnixIOException(int errorCode) : this(GetErrorMessage(errorCode), errorCode) { } /// /// Initializes a new instance of the class. /// /// The message that describes the error. #if NETSTANDARD [SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)] #endif public UnixIOException(string message) : base(message) { } /// public UnixIOException(string message, Exception inner) : base(message, inner) { } /// public UnixIOException(string message, int errorCode) : base(message, errorCode) { } #if ! NET8_0_OR_GREATER /// protected UnixIOException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endif private static string GetErrorMessage(int errorCode) { try { nint ptr = UnsafeNativeMethods.StrError(errorCode); return Marshal.PtrToStringAnsi(ptr); } catch { return $"Unknown error: 0x{errorCode:x}"; } } } }