Export (0) Print
Expand All

Silverlight Application Scripting Error Handling

Error Handling in Silverlight-based Scripting Applications

You can provide error-handling support in your Microsoft Silverlight-based scripting applications in a number of ways, depending on the type of the error. The onError event on the Silverlight plug-in can be used to handle parser errors, run-time errors, and other types of errors. A try/catch block can be placed around a synchronous method call, and errors resulting from the call can be handled in the catch block. Event handlers can be attached to asynchronous error events, such as the MediaFailed event. If you use Visual Studio, you can use the integrated JavaScript debugging support to set breakpoints and inspect values.

Note   Specific error messages are not covered in this article. If you would like to see lists of error messages and their meanings, see Error Messages.

This topic contains the following sections:

Using the Default OnError Event Handler

The samples in the Silverlight SDK use the JavaScript helper files, CreateSilverlight.js and Silverlight.js, which enable you to create a Silverlight plug-in in a platform-independent way. These files also provide a default event handler for the onError event. When you allow the onError property to default to null, or set the property to null, the default handler function defined in Silverlight.js is invoked when errors are encountered.

The onError handler is used for XAML parsing errors, errors that occur during load, run-time errors, errors in synchronous method calls that are not handled in a try/catch block, and asynchronous error events that do not have an attached event listener.

The default OnError event-handler function defined in the Silverlight.js file displays a dialog box. The following illustration shows the dialog when a scripting error is encountered in Microsoft Internet Explorer.

Alert dialog box for default event handler

Alert dialog box for default event handler

Defining an OnError Event Handler

You can define an error handler for your Silverlight-based application by setting the OnError property of the Silverlight plug-in to a custom event-handler function.

The onError event handler takes two parameters: the sender object and the event arguments. The sender is the object on which the error occurred. The second parameter is an instance of the ErrorEventArgs object or one of its derived objects, ParserErrorEventArgs or RuntimeErrorEventArgs, depending on the type of error.

The following table lists the properties on a ErrorEventArgs object. These properties are common to all error events handled by onError.

Property Description
errorMessage Identifies the message that is associated with the error event.
errorType Identifies the type of error, defined as a value of the ErrorType enumeration.
errorCode Specifies the code associated with the error event.

The following table lists the properties that are specific to parser errors, which are defined on a ParserErrorEventArgs object.

Property Description
charPosition Identifies the character position in which the error occurred.
lineNumber Identifies the line on which the error occurred.
xamlFile Identifies the XAML file in which the error occurred.
xmlAttribute Identifies the XML attribute in which the error occurred.
xmlElement Identifies the XML element in which the error occurred.

The following table lists properties that are specific to run-time errors, which are defined on a RuntimeErrorEventArgs object.

Property Description
charPosition Identifies the character position in which the error occurred.
lineNumber Identifies the line on which the error occurred.
methodName Identifies the method that is associated with the error.

The following JavaScript example shows how to set the OnError event handler to a user-defined function named OnErrorEventHandler.

JavaScript
    //example calls, please replace with calls that match your site's requirements    
    Silverlight.createObject(xamlFile, pe, "AgControl1",
                                 {width:'600px', height:'600px', inplaceInstallPrompt:false, background:'#FFFFFF', isWindowless:'false', framerate:'24', version:'1.0'},
                                 {onError:null, onLoad:null},
                                 null);


The following JavaScript example shows the associated event-handler function for the OnError event of the Silverlight plug-in. The ErrorType property on the ErrorEventArgs is checked to determine the specific type of error. If the error is a run-time or parser error, additional error information is added to the display message.

JavaScript
function OnErrorEventHandler(sender, errorArgs)
{
    // The error message to display.
    var errorMsg = "Silverlight Error: \n\n";
    
    // Error information common to all errors.
    errorMsg += "Error Type:    " + errorArgs.errorType + "\n";
    errorMsg += "Error Message: " + errorArgs.errorMessage + "\n";
    errorMsg += "Error Code:    " + errorArgs.errorCode + "\n";
    
    // Determine the type of error and add specific error information.
    switch(errorArgs.errorType)
    {
        case "RuntimeError":
            // Display properties specific to RuntimeErrorEventArgs.
            if (errorArgs.lineNumber != 0)
            {
                errorMsg += "Line: " + errorArgs.lineNumber + "\n";
                errorMsg += "Position: " +  errorArgs.charPosition + "\n";
            }
            errorMsg += "MethodName: " + errorArgs.methodName + "\n";
            break;
        case "ParserError":
            // Display properties specific to ParserErrorEventArgs.
            errorMsg += "Xaml File:      " + errorArgs.xamlFile      + "\n";
            errorMsg += "Xml Element:    " + errorArgs.xmlElement    + "\n";
            errorMsg += "Xml Attribute:  " + errorArgs.xmlAttribute  + "\n";
            errorMsg += "Line:           " + errorArgs.lineNumber    + "\n";
            errorMsg += "Position:       " + errorArgs.charPosition  + "\n";
            break;
        default:
            break;
    }
    // Display the error message.
    alert(errorMsg);
}
f

Synchronous Method Calls and try/catch Blocks in JavaScript

Synchronous method calls block the calling function until the call returns. A try/catch statement enables you to test a block of JavaScript code for errors. The try block contains the code to be run, and the catch block contains the code to be executed if an error occurs.

If a synchronous method call fails and the method call is in a try/catch block, an error object, described in "ECMAScript Language Specification" (ECMA-262), is passed to the catch block and an onError event is not raised. Because an onError event is not raised, the onError event handler will not be called. If a synchronous method call fails and the method call is not inside a try/catch block, an onError event is raised and routed to the onError handler of the Silverlight plug-in. The ErrorType in the event arguments sent to the onError handler will be set to RuntimeError.

The only Silverlight-specific error information returned to the catch block through the error object is the ErrorMessage and on Internet Explorer only, the ErrorCode. The message property on the error object is set to the error message.

The try/catch functionality is currently supported on all browsers and operating systems that Silverlight supports except for Apple Safari and Macintosh. Because of this limitation, we recommend using onError for all synchronous run-time methods.

The following JavaScript example shows how to use a try/catch statement to handle errors generated from the Play method.

JavaScript
    // Get the MediaElement object.
    var player = sender.findName("MediaPlayer");

    try
    {
        // Attempt to start the media.
        player.play();
    }
    catch(errorObj)
    {
        // Perform necessary error handling.
    
        // Display the message of the Error Object.
        alert(errorObj.message);
    }

The following illustation shows the resulting error message that is displayed when the call to play in the previous example fails.

Error message

Error message

Silverlight Asynchronous Error Events

An asynchronous call returns control immediately after it has been called. An error that occurs during the asynchronous call will raise an error event that is specific to the type of call. If a handler is not attached to the event, an onError event will be raised and handled by the handler defined on the Silverlight plug-in. An example of an asynchronous error event is the MediaFailed event.

The following XAML shows how to attached an event handler to the MediaFailed event.

XAML
  <MediaElement x:Name="MediaPlayer" MediaFailed="MediaFailedHandler" />

The following JavaScript code shows an event handler for the MediaFailed event.

JavaScript
function MediaFailedHandler(sender, args)
{

    // Create basic error message.
    var errorMsg = "\n Media Error Message     \n" ;

    // Add Media information.
    errorMsg += "MediaElement Name: " + sender.Name + "\n";
    errorMsg += "Media File Name: " + sender.Source + "\n";

    // Display error information.
    alert(errorMsg);  
}

Enabling JavaScript Debugging in Visual Studio

When you create a Silverlight-based application in Visual Studio, you can use Visual Studio to debug your JavaScript code. You can set breakpoints, view and modify variable values, and run script in the Immediate window. To enable JavaScript debugging in Visual Studio, you need to clear the "Disable script debugging" settings in Internet Explorer. By default, the check boxes for these settings are selected. The following illustration shows the check boxes after they have been cleared.

Internet Explorer advanced options

Internet Explorer advanced options

After you clear the "Disable script debugging" settings, you can set breakpoints in your JavaScript code. The following illustration shows the breakpoints in Visual Studio.

Setting breakpoints

Setting breakpoints

Note   If you are running Windows Vista, you must run Visual Studio with administrator access; otherwise, breakpoints will be ignored.

See Also

Error Messages
Silverlight Events
Overviews and How-to Topics

Community Additions

Show:
© 2014 Microsoft