using Unosquare.Swan; using System; using System.Runtime.InteropServices; namespace Unosquare.RaspberryIO.Native { /// /// 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(Int32 errorCode, String component) : base($"A hardware exception occurred. Error Code: {errorCode}") { this.ExtendedMessage = null; try { this.ExtendedMessage = Standard.Strerror(errorCode); } catch { // TODO: strerror not working great... $"Could not retrieve native error description using {nameof(Standard.Strerror)}".Error(Pi.LoggerSource); } this.ErrorCode = errorCode; this.Component = component; } /// /// Gets the error code. /// /// /// The error code. /// public Int32 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() => $"{this.GetType()}{(String.IsNullOrWhiteSpace(this.Component) ? String.Empty : $" on {this.Component}")}: ({this.ErrorCode}) - {this.Message}"; } }