Note: This article was created based on Flex 2. Minor changes in the description and code may be necessary before it can be applied to Flex 3.
Invoking remote methods, passing arguments and receiving responses are the most fundamental remote procedure call (RPC) concepts. However, an equally important, but often not as well understood or used capability is handling errors occurring during remote method invocations. This article reviews the process of exception propagation and demonstrates the code for processing data delivered with server-side exceptions and errors.
My previous article, Invoking .NET objects using the Flex RemoteObject API, describes how to invoke .NET methods from Flex. I recommended that you follow the steps in that article first, to ensure your development environment is configured so that you can invoke .NET methods from Flex.
The examples and solution demonstrated in this article uses WebORB for .NET, a product by Midnight Coders that facilitates connectivity between Flex and .NET. WebORB functions as a gateway between Flex clients and .NET objects. Using WebORB, your Flex applications can use the standard remoting API to communicate with .NET.
The Flex remoting API centers on the RemoteObject class
and RemoteObject MXML tag. When declaring a remote object proxy, you can
specify error handling functions attached to the proxy. For example, the
following code creates a remote object and adds two error handlers. The gotError function is added at the proxy
level, while the helloWorldFailed is added at the function level:
var myService:RemoteObject = new RemoteObject( "GenericDestination" );
myService.source = "examples.ExceptionsTest";
myService.addEventListener( FaultEvent.FAULT, gotError );
myService.helloWorld.addEventListener( FaultEvent.FAULT, helloWorldFailed );
public function gotError( evt:FaultEvent ):void
{
}
public function helloWorldFailed( evt:FaultEvent ):void
{
}
Both event listener functions in the above example handle
errors occurred during remote method invocations issued through the myService object. The function argument
is an object of the mx.rpc.event.FaultEvent type. The object contains some information about the exception, such as error
message, error code, or stack trace.
Since the gotError method is attached directly to the remote object reference, it becomes a
generic error handler. Flex invokes it any time there is an error from a method
invocation which does not have its own error handler function. For example, suppose
the remote object shown above invokes the getData method. The method does not have an error event listener registered with the
method. As a result, in case of an error, Flex delivers it to the gotError handler. (see Figure 1).

Figure 1. Processing errors with a generic fault handler
In case of the helloWorld method invocation, the remote
object has an error handler attached to that function. As a result, if an
exception occurs, it will be delivered as a FaultEvent to the helloWorldFailed function.
The .NET framework and the languages it supports provide a rich and extensible mechanism for raising and handling system and application-level exceptions. Application code can create custom exception classes or use the ones built into the framework's class library. The example below demonstrates raising a custom exception:
public float getQuote( String tickerSymbol )
{
float quote = 0;
if( tickerSymbol == null )
throw new UnknownTickerException();
return quote;
}
The method below causes a "division-by-zero" exception if the second argument is zero:
public float doDivision( int arg1, int arg2 )
{
return arg1 / arg2;
}
If the Flex client invokes the methods shown above using the
RemoteObject API/MXML, it is reasonable to expect that the exceptions must be
delivered to the client as FaultEvent objects. When the Flex client invokes .NET methods via WebORB, the server
includes special logic for handling exceptions raised from the invoked methods.
If an exception occurs, WebORB serializes it as FaultEvent so the client can process it in the fault
handler function.
The example below is a complete application demonstrating
various types of exceptions raised by the .NET code. The Flex client code
demonstrates how the server-side exceptions can be processed on the client and
what data various properties of the received FaultEvent objects contain.
Consider the following C# code:
using System;
using System.Collections;
using System.Text;
namespace Remoting.Examples
{
public class ExceptionsTest
{
public void divByZero()
{
int zero = 0;
int five = 5;
int result = five / zero;
}
public void NPE()
{
Hashtable hash = new Hashtable();
hash.Add( null, null );
}
public void throwException()
{
throw new MyException( "this is a custom application exception" );
}
}
public class
MyException : Exception
{
public MyException( String message )
: base( message )
{
}
}
}
The following is the same code written in VB.NET:
Imports System
Imports System.Collections
Imports System.Text
Namespace Remoting.Examples
Public Class
ExceptionsTest
Public Sub divByZero()
Dim zero As Integer = 0
Dim five As Integer = 5
Dim result As Integer = five / zero
End Sub
Public Sub NPE()
Dim hash As New Hashtable()
hash.Add(Nothing, Nothing)
End Sub
Public Sub throwException()
Throw New MyException("this is a custom application exception")
End Sub
End Class
Public Class MyException Inherits Exception
Public Sub New(ByVal message As String)
MyBase.New(message)
End Sub
End Class
The divByZero() method
raises a "division-by-zero" exception.
The NPE()method
adds null to a hashtable, which raises NullReferenceException.
The throwException() method raises a custom exception.
The Flex client application invokes each of the methods
above and displays properties of the FaultEvent object in the corresponding fields. The user interface of the client is shown
below (see Figure 2):

Figure 2. The user interface of the client
The following ActionScript/MXML code creates a remote object and invokes the methods above:
// declare a remote object variable
private var exceptionService:RemoteObject;
// the init() function is called on the creationComplete event
private function init():void
{
exceptionService = new RemoteObject( "GenericDestination" );
exceptionService.source = "Remoting.Examples.ExceptionsTest";
exceptionService.addEventListener( FaultEvent.FAULT, gotError );
}
private function gotError( fault:FaultEvent ):void
{
Alert.show("Server reported an error-" + fault.fault.faultString);
faultCodeField.text = fault.fault.faultCode;
faultStringField.text = fault.fault.faultString;
faultDetailField.text = fault.fault.faultDetail;
nameField.text = fault.fault.name;
messageField.text = fault.fault.message;
}
<mx:Panel width="100%" height="100%" layout="absolute" title="Exception Handling Example">
<mx:Button x="25.5" y="67" width="205" label="Generate Division by Zero" click="exceptionGenService.divByZero()"/>
<mx:Button x="25.5" y="112" width="205" label="Generate NullPointerException" click="exceptionGenService.NPE()"/>
<mx:Button x="25.5" y="158" width="205" label="Generate Application Exception" click="exceptionGenService.throwException()"/>
<mx:TextArea x="20" y="20" width="216" height="43" textAlign="center" borderStyle="none">
<mx:text>Click a button below to generate an exception on the server</mx:text>
</mx:TextArea>
<mx:Canvas x="263" y="20" width="345" height="199" borderStyle="solid">
<mx:Text x="28" y="20" text="faultString:"/>
<mx:Text x="28" y="57" text="faultDetail:"/>
<mx:Text x="31" y="98" text="faultCode:"/>
<mx:Text x="34" y="134" text="message:"/>
<mx:Text x="53" y="169" text="name:"/>
<mx:Label x="103" y="20" id="faultStringField" width="230"/>
<mx:Label x="103" y="57" id="faultDetailField" width="230"/>
<mx:Label x="103" y="98" id="faultCodeField" width="230"/>
<mx:Label x="103" y="134" id="messageField" width="230"/>
<mx:Label x="103" y="169" id="nameField" width="230"/>
</mx:Canvas>
<mx:Text x="273" y="11" text="Exception Details" opaqueBackground="0xffffff"/>
</mx:Panel>
The screenshot below demonstrates the output in the application when it received an exception (see Figure 3):

Figure 3. Output in the application when it received an exception
The source code for both client and server applications are available in the sample files.
Mark Piller is the founder and Chief Architect of Midnight Coders, an innovative and forward-thinking company specializing in RIA integration technologies, professional services and training. Mark has over 15 years of software development experience. For the past five years he has been specializing in building software infrastructure products designed to integrate Flex, Flash, and AJAX applications with a variety of backend systems, including .NET, Java, PHP, and Ruby on Rails. Mark is very passionate about ease-of-use of software and prides himself in creating technologies that clearly demonstrate that quality.