Xbasic GuideCapturing and Logging Errors

If an unexpected problem occurs when a script executes (i.e., a runtime error), Xbasic generates an error message. Unhandled errors may be shown to the user if they occur in an Ajax callback or server-side event. Because Xbasic runtime errors are often cryptic and cannot be fixed by the end-user, you want to include error handling to trap and log errors when they happen.

ON ERROR GOTO

An easy way to avoid sending cryptic error messages to your users is to use an error handler. The ON ERROR...GOTO statement can be wrapped around any Xbasic code to add error handling. For example:

FUNCTION myFunction AS C ()

ON ERROR GOTO HandleError

    'Xbasic Code to Execute

    'If we reach this point, no errors occurred!
    'Exit the function to prevent executing the HandleError code
    EXIT FUNCTION

HandleError:
    'Xbasic to handle the error
    'Get the error code:
    err = error_code_get()
    'Get the error message:
    msg = error_text_get(err)

    'Log error message to TRACE log on server:
    log_msg = "Encountered Error #" + err + " in myFunction(): " + msg
    TRACE.writeLn(log_msg,"myFunction")

    myFunction = "Problem executing callback."

END FUNCTION

A label defines a place that can be jumped to using the GOTO statement. The label and error handling code is usually defined at the end of your script.

labelname:

The label to go to is specified at the end of the ON ERROR...GOTO line at the beginning of your script:

ON ERROR GOTO labelname

Unlike IF statements, when the label is encountered after an ON ERROR...GOTO declaration, it is not skipped. A label is simply a named location that can be jumped to using the GOTO statement. In order to prevent the execution of error-handling code specified after the label, you must use an END, EXIT FUNCTION, or RETURN statement before the label is encountered.

Logging: Using the Trace Log

Log files are useful for recording information about events in a published application. If an error occurs in your application, you can use a log file to capture the error message and other details that you need to know to diagnose and correct the issue. The Trace Log is an ideal place to write out error information. The Trace Log is available both in the IDE (the Trace window) and in a deployed application (the Trace Log folder).

To send text output to the Trace Log, you can use the TRACE.writeLn() method. The TRACE.writeLn() method takes two parameters: the message to write to the Trace Log and an optional log name. For example, run the following code in the Interactive Window:

TRACE.writeLn("Log message","My Log")

To view the Trace Log, select View > Trace Window from the main menu on the Web Projects Control Panel. Locate the "My Log" tab in the Trace Window and open it. You should see the message "Log message" in the message window:

images/image011.png

If you do not specify a log name for the second parameter, the message is written to the "User" log.