#nullable enable
using System;
using System.Runtime.InteropServices;
namespace Unosquare.RaspberryIO.Abstractions.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 {
// Ignore
}
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() => $"{nameof(HardwareException)}{(String.IsNullOrWhiteSpace(this.Component) ? String.Empty : $" on {this.Component}")}: ({this.ErrorCode}) - {this.Message}";
}
}