Throwing an error when working with PHP and AMF

So you have PHP on your server, and Flex (web or AIR application) on your client. You also use AMF / remoting to communicate between the client, and the server. How do you send an error from the server to the client? You may find yourself in situations when you want to bubble up an error from the PHP side up to the Flex client, where you can display it to the user.

So how do you do this?

As a matter of fact it is pretty simple. As a starting point you can have a look at the two articles I wrote on PHP and AMF ZendAMF and AMFPHP. You can use the projects that you find attached there.

Basically, the way to do this is by throwing an Exception from your PHP file. This exception will bubble up to Flex, wrapped into a FaultEvent. If you register a listener on the RemoteObject for the fault event, then you are done!

Below is sample pseudo code showing you can do it.

PHP code

Suppose you expose a PHP class called MyService, which has a method getData(). This is how you can throw an error:

   1: class MyService {
   3:     public function getData() {
   4:         if (some_condition_is_false) {
   5:             $errorCode = 1;
   6:             throw(new Exception('the error message you want', $errorCode));
   7:         }
   8:     }
  10: }

So basically, you create an Exception passing two arguments to the constructor: a string (the error message), and a integer (the error code).

Flex code

And here is the code for the Flex side. I have the RemoteObject and the listener function for the fault event. I chose to display the error details using an alert.

   1: private function faultListener(event:FaultEvent):void {
   2: + ": " + event.fault.faultString, "Error");
   3: }
   4: ...
   5: <mx:RemoteObject id="myRemote" destination="zend" source="MyService" showBusyCursor="true" fault="faultListener(event)">
   6:     <mx:method name="getData" result="getDataListener(event)"/>
   7: </mx:RemoteObject>

On the fault event, you can find the error code you sent from PHP using event.fault.faultCode, the error message using event.fault.faultString, and the file and the line number from where the exception was thrown using event.fault.faultDetail.

Note: It seems that for the ZendAMF, the exception doesn’t pass all the information back to Flex. I suspect there is a problem in the PHP serializer, and thus only the error code gets to Flex.

3 thoughts on “Throwing an error when working with PHP and AMF

  1. in your bootstrap has setProduction(false) you will get the detailed information. Otherwise we do not return that data as an exception could have sensitive information that could create a security risk. Especially in the case of a db connection failure.

  2. Pingback: Symfony, Flex, and Facebook API « Footprints

Leave a Reply