Tutorial 2-4: Error handling
Until now, the example code did not check the function return values for errors. In an actual application, the return value of each function must be checked and any detected errors handled properly.
Each WMX3 function call returns an error code that can be converted to an error message string with the ErrorToString function. The None error code indicates success.
The following adds basic error checking to the example code. If an error occurs, processing is halted, communication is stopped, and the device is closed.
WMX3Api wmxlib = new WMX3Api();
int err;
Console.WriteLine("Starting application...");
err = wmxlib.CreateDevice("C:\\Program Files\\SoftServo\\WMX3", DeviceType.DeviceTypeNormal);
if (err != ErrorCode.None) {
Console.WriteLine("Failed to create device. Error={0} ({1})",
err, WMX3Api.ErrorToString(err));
goto exit;
}
err = wmxlib.StartCommunication(5000); //Wait for up to 5 seconds for communication to start
if (err != ErrorCode.None) {
Console.WriteLine("Failed to start communication. Error={0} ({1})",
err, WMX3Api.ErrorToString(err));
goto exit;
}
System.Threading.Thread.Sleep(5000); //Wait five seconds before stopping communication
exit:
err = wmxlib.StopCommunication();
if (err != ErrorCode.None) {
Console.WriteLine("Failed to stop communication. Error={0} ({1})",
err, WMX3Api.ErrorToString(err));
}
err = wmxlib.CloseDevice();
if (err != ErrorCode.None) {
Console.WriteLine("Failed to close device. Error={0} ({1})",
err, WMX3Api.ErrorToString(err));
}
wmxlib.Dispose();
Console.WriteLine("Press any key to exit.");
Console.ReadKey();