Flex and ColdFusion: Returning error types

When I write a service layer for a Flex application (or other types of clients), I often make heavy use of <cfthrow> tags in my service CFC's.

For example, if I were building a Flex shopping cart and a user wants to do service.placeOrder(), but placeOrder() checks user authentication status and user.isLoggedIn() is false, I need to indicate not just a failure but what went wrong back to the client.

In pure ColdFusion, I'd do this with a custom type attribute on <cfthrow>:

<cfthrow
   type="cartService.userNotLoggedIn"
   message="User must be logged in!"
/>

Flex, however, doesn't get to see the value of the type attribute: it just gets a plain exception without much information other than the value of the 'message' attribute, which I like to leave human readable and populate with helpful text.

To send back the "type" of exception, set both the type and the errorCode attributes:

<cfthrow
   type="cartService.userNotLoggedIn"
   errorCode="cartService.userNotLoggedIn"
   message="User must be logged in!"
/>

Now, in your Flex app, you can test what went wrong by testing the faultCode property of the fault, which'll be populated by the errorCode's value:

private function placeOrderFaultHandler(info:Object):void
{
   var fault:Fault = FaultEvent(info).fault;

   switch (fault.errorCode)
   {
      // These work great as constants on a CartServiceFaults class.
      case "cartService.userNotLoggedIn":
         dostuff();
         break;
   }
}

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
EXCELLENT. Good simple tip. Thx.
# Posted By Joshua Curtiss | 4/25/08 3:01 PM
© 2008 Firemoss, LLC
BlogCFC was created by Raymond Camden. This blog is running version 5.8.001.