namespace Unosquare.RaspberryIO.Native { using Swan; using System; using System.Runtime.InteropServices; /// /// Represents a low-level exception, typically thrown when return codes from a /// low-level operation is non-zero or in some cases when it is less than zero. /// /// public class HardwareException : Exception { /// /// Initializes a new instance of the class. /// /// The error code. /// The component. public HardwareException(int errorCode, string component) : base($"A hardware exception occurred. Error Code: {errorCode}") { ExtendedMessage = null; try { ExtendedMessage = Standard.Strerror(errorCode); } catch { // TODO: strerror not working great... $"Could not retrieve native error description using {nameof(Standard.Strerror)}".Error(Pi.LoggerSource); } ErrorCode = errorCode; Component = component; } /// /// Gets the error code. /// /// /// The error code. /// public int ErrorCode { get; } /// /// Gets the component. /// /// /// The component. /// public string Component { get; } /// /// Gets the extended message (could be null). /// /// /// The extended message. /// public string ExtendedMessage { get; } /// /// Throws a new instance of a hardware error by retrieving the last error number (errno). /// /// Name of the class. /// Name of the method. /// When an error thrown by an API call occurs public static void Throw(string className, string methodName) => throw new HardwareException(Marshal.GetLastWin32Error(), $"{className}.{methodName}"); /// public override string ToString() => $"{GetType()}{(string.IsNullOrWhiteSpace(Component) ? string.Empty : $" on {Component}")}: ({ErrorCode}) - {Message}"; } }