We can invoke Java objects using BlazeDS. For details on how to invoke Java objects from flex visit this URL Invoking Java methods from Flex
It’s a common practice in Java methods to throw Exceptions to indicate that something has failed. These exceptions can be either custom exceptions or inbuilt exceptions. It is also common that we include some message in that exception, which describes the problem caused. Now how do we get that message and display it in Flex applications? What if you want to add some other information to the Exception you are throwing and you want to access that information too?
You can do this
BlazeDS will by default serialize any Throwable type object. All you need to do is to access the objects.
Accessing the Throwable object in Flex
RemoteObject component invokes the fault event when an error occurs while remote method invocation. The fault event handler is provided with the FaultEvent object. This FaultEvent object has property named message of type mx.messaging.messages.ErrorMessage. The message property holds the Throwable object from the Java method in the rootCause property. We need to use this rootCause property to retrieve the properties which are set to the Throwable object in Java. All the public properties from the Throwable object are available.
We will see a sample application. In this application I am creating a custom Exception and adding a getter method to that, which will return my custom data. From the Flex application I will access both the error message and the custom data.
MyException.java
public class MyException extends Exception {
public MyException(String message) {
super(message);
}
public String getMyName(){
return “Sujit Reddy G”;
}
}
Method throwing exception
This method will throw the custom exception created above, add this method to a Java class. Invoke the below method using RemoteObject component in Flex.
public void throwCheckedException() throws Exception{
throw new MyException(“This is a checked exception”);
}
Reading values in Flex application
We add the method below as the fault event handler to the RemoteObject component in the Flex application. You can see that we accessed the rootCause object to retrieve the properties of the custom Exception object returned from the Java method.
private function handleException(event:FaultEvent):void{
var errorMessage:ErrorMessage = event.message as ErrorMessage;
Alert.show(errorMessage.rootCause.message);
Alert.show(errorMessage.rootCause.myName);
}
We are adding the above method as fault event handler to the RemoteObject component.
<mx:RemoteObject id=”exceptionObj” destination=”CreatingRpc” result=”handleRPC(event)”
fault=”handleException(event)”/>
Invoking the method in the Java class on button click
<mx:Button label=”Invoke Exception” click=”exceptionObj.throwCheckedException()”/>
You can also use the flex.messaging.MessageException. This class is packaged in the flex-messaging-core.jar. You should throw MessagException instead of MyException or any custom exception created. MessageException provides a property named extendedData, which is a HashMap. You can add any data to this property and access it from the Flex application using ErrorMessage(event.message).extendedData.
That’s it
let me know if you have problem implementing this


March 4, 2008 at 9:53 am
Thanks a lot, it was just what I was searching for !
March 4, 2008 at 7:36 pm
I’ve tried to use your code to catch the authentication errors. At the server side, I’ve set the auth-method to Custom (for Tomcat authentication). And when I pass the wrong credentials from my flex code I was hoping to handle the exception. But I was not able to get the faultString in the Flex application.
private function handleException(event:FaultEvent):void
{
// var errorMessage:ErrorMessage = event.message as ErrorMessage;
//Alert.show(errorMessage.rootCause.message);
// Alert.show(errorMessage.rootCause.myName);
Alert.show(“Error Happened “);
Alert.show((ErrorMessage)(event.message).extendedData.faultString);
}
For the second Alert.show I get
TypeError: Error #1009: Cannot access a property or method of a null object reference.
Here’s my tomcat console output. The ClientID is the only part I was able to access from my Flex front end so far.
[BlazeDS] 11:28:13.906 [DEBUG] Serializing AMF/HTTP response
Version: 3
(Message #0 targetURI=/2/onStatus, responseURI=)
(Typed Object #0 ‘flex.messaging.messages.ErrorMessage’)
headers = (Object #1)
rootCause = null
body = null
correlationId = “2F1126D7-5658-BE40-E27C-7B43F3C5DCDD”
faultDetail = null
faultString = “Login required before authorization can proceed.”
clientId = “C4F0E77C-3208-ECDD-1497-B8D070884830″
timeToLive = 0.0
destination = “books”
timestamp = 1.204658893906E12
extendedData = null
faultCode = “Client.Authentication”
messageId = “C4F0E77C-321E-6FCE-E17D-D9F1C16600A8″
March 6, 2008 at 1:21 pm
Hi Eric,
Modify your code to the below one
Alert.show(event.message.faultString)
faultString is a property of the ErrorMessage, not the extendedData.
Hope this helps.
March 7, 2008 at 10:30 pm
Sujit,
Yes it helped, thanks; posted code snippet was from my fault event handler, so I had to change it to
Alert.show(event.fault.faultString);
I have another question now; it is not directly related with this thread but I’ll shoot it;
I have a custom flex user login form. Which calls the setCredential on my remote object. it works the first time, but if in the same session, if I want to switch to another user, the call to
myRemoteObj.setCredentials(userid,pwd)
doesn’t work. it returns an exception about it can not re-authenticate. As a workaround I have changed it to
myRemoteObj.logout();
myRemoteObj.setCredentials(userid,pwd)
But this returns a Action Script Error (A popup – looks like a Adobe Flash Player Console)
Error: Credentials cannot be set while authenticating or logging out.
My guess is setCredentials code is executed before the logout call is not finished. What can be done ?
March 10, 2008 at 1:16 am
Eric,
Trying doing channelSet.disconnect() or disconnectAll();
My question to you is, in a fresh browser window, if a login attempt fails, does you browser present a login prompt for that remoting endpiong? That’s the problem I have right now. I have login form in Flex that calls an authenticate operation on my remote object. However, the remote object requires a login before calling the authenticate method. Weird isn’t it?
thanks.
March 12, 2008 at 11:48 pm
Mick,
You need to make your remote object which does the authentication public. Otherwise it is catch22. Make sure the remote object is not secured anyway through URL path or other means.
BTW, channelSet.disconnectAll() did NOT do it for me. I still get the same error when I try to pass the new credentials afterwards
Error: Credentials cannot be set while authenticating or logging out.
March 28, 2008 at 2:40 pm
Why can RemoteClass not be used for this?
April 4, 2008 at 2:54 pm
You meant to say you want to create a AS class which is of the type Exception class thrown by your Java and map both? I think that will work.
May 28, 2008 at 1:35 pm
Hi Sujit,
Thank you for this blog. It helped me lot in understanding exception handling concept.
I am new to Flex.
I tried to run the same code what is mentioned in this blog, but I am unable to see either name or any other custom message, I can see only “HTTP Request Error”. If possible could you please send me a detailed code snippet Please.
If I tried to print the error object, I am getting below message
(mx.messaging.messages::ErrorMessage)#0
body = (Object)#1
clientId = “DirectHTTPChannel0″
correlationId = “11981C27-5A48-7E75-58F6-2F8F3E8E1430″
destination = “”
extendedData = (null)
faultCode = “Server.Error.Request”
faultDetail = “Error: [IOErrorEvent type="ioError" bubbles=false cancelable=false eventPhase=2 text="Error #2032: Stream Error. URL: http://10.20.14.40:8080/SampleHandler/SampleHandler"]. URL: http://10.20.14.40:8080/SampleHandler/SampleHandler”
faultString = “HTTP request error”
headers = (Object)#2
messageId = “701C98FC-8E91-E1A0-F489-2F8F3FC64A65″
rootCause = (flash.events::IOErrorEvent)#3
bubbles = false
cancelable = false
currentTarget = (flash.net::URLLoader)#4
bytesLoaded = 0
bytesTotal = 0
data = (null)
dataFormat = “text”
eventPhase = 2
target = (flash.net::URLLoader)#4
text = “Error #2032: Stream Error. URL: http://10.20.14.40:8080/SampleHandler/SampleHandler”
type = “ioError”
timestamp = 0
timeToLive = 0
Thanks for your precious time.
Awaiting for your reply.
thank you
Sreekanth
June 17, 2008 at 7:53 am
Hi, I have tried with suceed to map Java exceptions and AS3 classes with RemoteObject, but now I have to make the same with Java execptions from Web services. I thought it ‘d be possible to cast event.message in ErrorMessage but it doesn’t work.
Please i need some help.
June 25, 2008 at 12:19 pm
Hi Julien,
I never tried this. I can suggest you to have a look at the URL below and see if you solve your problem.
http://livedocs.adobe.com/flex/3/langref/mx/rpc/xml/IXMLSchemaInstance.html
Hope this helps.
June 25, 2008 at 12:25 pm
Hi Sreekanth,
Looks like you did not configure your end point properly. Usually the end point URL for a remoting destination ends with messagingbroker/amf …. The URL http://10.20.14.40:8080/SampleHandler/SampleHandler
Please check out the URL below and see if you configured the destination properly.
http://sujitreddyg.wordpress.com/2008/01/14/invoking-java-methods-from-adobe-flex/
Hope this helps.
June 25, 2008 at 12:27 pm
Hi Sreekanth,
Looks like you did not configure your end point properly. Usually the end point URL for a remoting destination ends with messagingbroker/amf …. The URL http://10.20.14.40:8080/SampleHandler/SampleHandler
Please check out the URL below and see if you configured the destination properly.
http://sujitreddyg.wordpress.com/2008/01/14/invoking-java-methods-from-adobe-flex/
Hope this helps.
July 5, 2008 at 6:01 am
Hi Sujit,
I hope you will be fine. I have a problem with a SOAP Service. I invoke a method called getSongsOfContext(applicationID,applicationPass,userID,userPass,contextBlock,duration).
But i get an error called “[RPC Fault faultString="HTTP request error" faultCode="Server.Error.Request" faultDetail="Error: [IOErrorEvent type="ioError" bubbles=false cancelable=false eventPhase=2 text="Error #2032"]. URL: http://webservice.aristomusic.com:10808/production/services/Aristo-WS“]”.
The ContextBlock parameter of the SOAPService is a LIST on the backend JAVA server. I am initialization it as an Array because Flex help tells me that Array maps to the LIST class of JAVA. But still I get that error.
Could you please help. This component is very important part of my project. My money is stuck.
Cheers
Khawar
July 9, 2008 at 8:46 am
Hi Khawar,
It doesn’t look like there is a problem with the type conversion.
If you think that is the problem, then please check out if it is a sparse Array or dense Array. Depending on the Array the conversion varies. Please find more details on sparse and dense array and how they affect the conversion at the URL below.
http://livedocs.adobe.com/flex/3/html/data_access_4.html#202412
Hope this helps
July 28, 2008 at 8:30 am
i create a website which will help people who are interesting in Java. My website is new so it will get better with help of Java users.
August 6, 2008 at 6:51 pm
I get error message as follows on using Flex FDS. I guess it is getting null pointer and no error in console and I get this in trace in handleError function
ErrorMessage : (mx.messaging.messages::ErrorMessage)#0
body = (null)
clientId = (null)
correlationId = “6AF204EA-3614-9028-33B1-99560682484F”
destination = “swingsService”
extendedData = (null)
faultCode = “Server.Processing”
faultDetail = (null)
faultString = “java.lang.NullPointerException : null”
headers = (Object)#1
messageId = “615B081E-AC4E-EA2B-0958-CE8DC326D0A7″
rootCause = (Object)#2
cause = (null)
localizedMessage = (null)
message = (null)
timestamp = 1218048296812
timeToLive = 0
August 7, 2008 at 2:31 pm
Hi Mohana,
Can you try and debug the rootCause object in the ErrorMessage. Try to find some error in the stdout of the web server.
Hope this helps.
August 11, 2008 at 9:55 am
Hi,
Julien, did you managed to map Java exceptions threw by a web service to ActionScript exception ?
I have the same problem and I would like some help if possible.
I have a java custom exception which is as followed :
public class MyException extends Exception {
public String messageLog;
public String messageEncoded;
public MyException () {
}
public MyException (String message) {
super(message);
}
Here are the setter/getter of the 2 attributes …
}
I have too a MyException in actionScript :
package MyPackage
{
[RemoteClass(alias="MyPackage.MyException")]
[Bindable]
public class MyException{
public var messageLog: String;
public var messageEncoded: String;
}
}
And I d’like to retrieve this exception in the fault method of the flex service.
private function onFault( event:FaultEvent) : void {
var myException:MyException = event.fault.rootCause as MyException;
}
but, the object myException is always NULL whereas event.fault.rootCause has values in it.
Do you have an idea to resolve my problem ?
Thank you for your answers !!
Bye
August 20, 2008 at 5:43 pm
Hi Sujit,
Can you please tell how to do Exception handling for Flex-HTTPServices communication.
Class on Backend is as below.
—————————————-
public class ServiceAcceptor extends javax.servlet.http.HttpServlet {
private Logger logger=Logger.getLogger(ServiceAcceptor.class);
public ServiceAcceptor() {
super();
}
public void init(){
// ClarityAgent.getInstance();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doAction(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doAction(request,response);
}
protected void doAction(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
IAction action = (IAction)ctx.getBean(“ServicesController”);
try{
action.doAction(request,response);
}catch(Exception e){
throw new ServletException(“Exception from BackEnd”);
}
}
———————————-
On flex side we see the following variables. I dont see the cutom error which I put on backend side.
———————————-
message = mx.messaging.messages.ErrorMessage (@b3e29d1)
body = Object (@b3ce269)
clientId = “DirectHTTPChannel0″
correlationId = “DB42658C-64A1-2618-156A-E11B7AFCE636″
destination = “”
extendedData = null
faultCode = “Server.Error.Request”
faultDetail = “Error: [IOErrorEvent type="ioError" bubbles=false cancelable=false eventPhase=2 text="Error #2032: Stream Error. URL: http://161.15.160.169:7070/ProductWS/services/GetClientReports"]. URL: /ProductWS/services/GetClientReports”
faultString = “HTTP request error”
headers = Object (@b3ce179)
messageId = “B355B8AC-7B18-AC77-5604-E11BA1FDC34A”
rootCause = flash.events.IOErrorEvent (@b1b83f9)
bubbles = false
cancelable = false
currentTarget = flash.net.URLLoader (@b3e2a81)
eventPhase = 2
target = flash.net.URLLoader (@b3e2a81)
text = “Error #2032: Stream Error. URL: http://161.15.160.169:7070/ProductWS/services/GetClientReports”
type = “ioError”
timestamp = 0
timeToLive = 0
————————————-
If you can find solution please let me know.
Thanks a lot in advance
Kranthi
November 16, 2008 at 6:55 pm
Really thanks alot for these great tutorials!
Your blog has valuable and great tutorials.
December 17, 2008 at 8:56 pm
Hi Sujit,
I am working on flex with java as backend and blazeds in the middle.
I found this doc very useful as this is what i have been looking for,
but i could not apply this exactly to my project as i don’t want to changed anything in my services, i cannot have my custom exceptions class,
but i want to get the error message from down the stack,
i could get the error message from down the stack in java using exception.getCause(),
can u suggest me a way to get this in flex.
Thankyou,
V.Kranthi.
December 18, 2008 at 2:11 pm
Hi Kranthi,
I don’t think you need to create custom exception classes. Even the regular Exception classes thrown are returned to you in Flex.
Hope this helps.
December 18, 2008 at 6:46 pm
HI Sujit,
Thankyou for the response,
you are right, even the regular exception class is throwing some error message,
i could get the base error with the rootCause object.
Thankyou,
Regards,
V.Kranthi.
April 7, 2009 at 6:50 pm
[...] Flex and Blaze DSBlazeDS and LCDS Feature differenceRendering PDF content in Adobe AIR applicationHandling Java Exceptions in Flex applicationAS3 library for Google Calendar (as3googlecalendarlib)Ask [...]
June 3, 2009 at 6:49 am
Very nice example and explanation. I am currently using this in our application project and it works like a champ. Much thanks for taking the time to create this explanation. Saved me many, many hours.
June 12, 2009 at 12:21 am
I was using your approach succesfully until we have switched using the Flex-Spring Integration.
After that I can no longer access my custom exception from Flex client, instead server returns a UndeclaredThrowableException just like reported here.
http://forum.springsource.org/showthread.php?t=72571
Can you think of a workaround ?
June 16, 2009 at 1:46 am
Thanks for this post! Exactly what I needed!
June 30, 2009 at 12:34 pm
Hi sujit
This exception handling is straight forward when we call a remote object method and add a Fault event listener to it. I have a case which is different.
details : From flex call a servlet to upload file from flex side. The servlet gets invoked and reads the data , does some processing by calling some helper classes. If any error occurs while processing i throw exception , which indirectly comes out of servlet as ServletException .
But at flex side we cannot add a fault event listener for uploading file. So how to catch such servlet exceptions….
Thanks & Regards
Jash