Handling Errors and Logging

From Phidgets Support
 Phidget Programming Basics: Handling Errors and LoggingTOC Icon.png Table of Contents

Nav Back Arrow.png Nav Back Hover.png WhiteTab1.png HoverTab1.jpg WhiteTab2.png HoverTab2.jpg WhiteTab3.png HoverTab3.jpg WhiteTab4.png HoverTab4.jpg WhiteTab5.png HoverTab5.jpg WhiteTab6.png HoverTab6.jpg WhiteTab7.png HoverTab7.jpg WhiteTab8.png HoverTab8.jpg WhiteTab9.png HoverTab9.jpg WhiteTab10.png HoverTab10.jpg WhiteTab11.png HoverTab11.jpg WhiteTab12.png HoverTab12.jpg WhiteTab13.png HoverTab13.jpg GreenTab14.png WhiteTab15.png HoverTab15.jpg WhiteTab16.png HoverTab16.jpg Nav Next Arrow.png Nav Next Hover.png


14 . Handling Errors and Logging

You've written your code, fixed the compiler errors, and yet, the program still isn't behaving as intended. The tools described on this page will help you further debug your program and figure out where in the code things are going wrong.

Errors and Error Events

The Phidget library uses errors and error events to communicate information about potential problems in your program. These can happen in-line in the form of an exception or error code (which generally indicate a problem in the code), and as Error Events (which generally indicate a problem with the Phidget's environment).

Errors from Function Calls

When a call to a Phidgets function fails it will throw an exception (or return an error code, depending on the language). It is important to check each function call for errors, and to catch and handle any errors.

Common causes of this type of error are the Phidget not being attached, or one of the values provided to the function being outside the valid range.

You can handle exceptions and return codes as follows:

try:
    ch.openWaitForAttachment(5000);
except PhidgetException as e:
    print("Failed to open: " + e.details)
try {
    ch.open(5000);
} catch (PhidgetException ex) {
    System.out.println("Failed to open: " + ex.getMessage());
}
try
{
    ch.Open(); //open the device
}
catch (PhidgetException ex)
{
    Console.WriteLine("Failed to open: " + ex.Description)
}
PhidgetDigitalInputHandle ch;
PhidgetReturnCode res;
...    
res = Phidget_openWaitForAttachment((PhidgetHandle)ch, 5000);
if (res != EPHIDGET_OK) {
    char* desc;
    Phidget_getErrorDescription(res, &desc);
    printf("Failed to open: (%d) %s\n", res, desc);
}

In JavaScript, there are two types of exceptions to handle. The first is used in synchronous functions only, and handled using the traditional try/catch block:

try {
     var tmp = ch.state
}
catch(err) {
     console.log("Failed to get state: " + err.message)
}

The second type is used for asynchronous functions, which return "promises", handled using the 'await' keyword in addition to a try/catch:

async function main() {
    ...
    try {
        await ch.open()
    }
    catch(err) {
         console.log('Error:' + err.message);
    })
}

When in doubt, check the Phidget22 API to see whether the function you're checking returns a promise or not.

The consequences of not handling errors correctly ranges from improper behavior, to the program crashing due to an unhandled exception. Programs should check for errors on each function call, and handle any errors.

Error Codes

Full descriptions of all error codes can be found in the Error Code List page.

Error Events

Error events are asynchronously generated by Phidget devices, and by the Phidget library itself.

These do not necessarily indicate a problem with your program, and often serve as a status update from your device that your program should know. For example, a DistanceSensor might send an OutOfRange error if it does not detect anything in its field of view, or a TemperatureSensor could send a Saturation error indicating its temperature reading is outside the valid range for the sensor.

Error events are also fired when network errors occur, or when the library is unable to handle incoming change events quickly enough (event handlers could be too slow).

We strongly recommend setting up an error event handler for your channels so your program can keep track of these error conditions.

#Declare the event handler
def onErrorHandler(self, code, description):
    print("Code: " + str(code))
    print("Description: " + description)
...
#Declare your object. Replace "DigitalInput" with the object for your Phidget
ch = DigitalInput()
...
#Assign the handler that will be called when the event occurs
ch.setOnErrorHandler(onErrorHandler)
//Declare the event listener
public static ErrorListener onError = new ErrorListener() {
    @Override
    public void onError(ErrorEvent e) {
        System.out.println("Code: " + e.getCode());
        System.out.println("Description: " + e.getDescription());
    }
};
...
//Declare your object. Replace "DigitalInput" with the object for your Phidget.
DigitalInput ch;
...
//Assign the event listener that will be called when the event occurs
ch.addErrorListener(onError);
//Declare the event handler
void error(object sender, Phidget22.Events.ErrorEventArgs e) {
    Console.WriteLine("Code: " + e.Code.ToString());
    Console.WriteLine("Description: " + e.Description);
}
...
//Declare your object. Replace "DigitalInput" with the object for your Phidget.
DigitalInput ch;
...
//Assign the handler that will be called when the event occurs
ch.Error += error;
//Declare the event handler
static void CCONV onErrorHandler(PhidgetHandle ph, void *ctx, Phidget_ErrorEventCode code, const char* description) {
    printf("Code: %d\n", code);
    printf("Description: %s\n", description);
}
...
//Declare your object. Replace "PhidgetDigitalInputHandle" with the handle for your Phidget object.
PhidgetDigitalInputHandle ch;
...
//Assign the handler that will be called when the event occurs
Phidget_setOnErrorHandler((PhidgetHandle)ch, onErrorHandler, NULL);
// Declare your object. Replace "DigitalInput" with the object for your Phidget
const ch = new phidget22.DigitalInput()

// Assign the handler that will be called when the event occurs
ch.onError = function(code, description) {
    console.log('Code: ' + code)
    console.log('Description: ' + description)
}

Full descriptions of all error event codes can be found in the Error Event Code List page.

Logging

You can enable logging to get more debugging information. This would happen at the very start of your program, before even initializing your software object or opening it. Logging lets you get feedback from the Phidget libraries about things happening behind the scenes.

from Phidget22.Devices.Log import *
from Phidget22.LogLevel import *

Log.enable(LogLevel.PHIDGET_LOG_INFO, "path/to/log/file.log")
Log.enable(LogLevel.INFO, null);
Log.Enable(LogLevel.Info, null);
PhidgetLog_enable(PHIDGET_LOG_INFO, NULL);

Client-side logging is not enabled in JavaScript. For library errors, you can check the console, and for communication errors, you can enable logging on the server side. For information on how to enable and access network server logs, see the Network Server Troubleshooting page.

When NULL is passed to enable() in the above examples, the logging system will output to STDERR.

For a more comprehensive look at the logging system in Phidget22, you can check out the Phidget Logging page.

Common Errors

For more information on how to handle common errors, such as sensor data being Out of Range or Invalid, see our page on Handling Out Of Range Errors.

Other Problems

If your Phidget is still not behaving as expected after handling errors and exceptions, have a look at our General Troubleshooting guide to track down the problem.