|
Returning useful error messages from CFC's in Flex |
One thing I've learnt from my flex to CFC tomfoolery is that sometimes flex doesn't diplay very good error messages from CFC's. This is no fault of flex, but more usually a problem with the interface between it, and CF, as most of the unfriendly error messages you get are http error strings, which usually get truncated as they are raw code, so you don't get to see the problem then either.
So you need more elegant error handling in your CFC's. (or whatever back end your using)
Here is a complete script as an example, we will go through it line by line:
2
3
4 <cffunction name="selectRecords" hint="Returns a query object based on an id" access="public" output="false" returntype="Any">
5 <cfargument name="id" required="true" type="String" hint="An id to use in the query below">
6
7 <cfset var message = "">
8
9 <!--- TRY the transaction below, throw a catch message --->
10 <cftry>
11
12 <cfif NOT isNumeric(arguments.id)>
13 <cfset message = "Id was not a number">
14 </cfif>
15
16 <cfquery datasource="#application.dsn#" name="qGetRecordById">
17 SELECT id, name, age, sex, telephone, mobile, address, postcode, county, country
18 FROM memberTable
19 Where id = #arguments.id#
20 </cfquery>
21
22 <cfcatch>
23 <cfthrow message="cfcatch.message">
24
25 <cfreturn message>
26 </cfcatch>
27
28 </cftry>
29
30 <cfreturn qGetRecordById />
31 </cffunction>
32</cfcomponent>
So its a normal component, with one function, it accepts an 'ID' and performs a query, and returns it.
I am setting a local variable at the top, 'message' that will only be created and used inside the scope of the CFC. Then we will 'TRY' and do our transaction. At this point I'm wrapping everything in the cftry tag so as to encapsulate any possible code errors or logic faults.
Any logic I have here will replace the value of 'message' if proven to be false, and return that message rather than the query object I was expecting.
But you'll notice the lines:
2 <cfthrow message="cfcatch.message">
3
4 <cfreturn message>
5 </cfcatch>
This will catch any errors from the try block, and throw them to flex. In this way flex receives the message in the throw command, not a http response message when the CFC breaks.
This is obviously a Coldfusion - CFC specific example, but I've seen very similar error trapping in php, working in exactly the same way, so it really doesn't matter what back end your using with flex.