2009-11-02 54 views
2

我在CFC文件中的函數,這將.CFM文件被稱爲像下面如何從CFC異常詳細文件

<cffunction name="cftest" access="public" returntype="query" output="true" hint="Function returns Records"> 

     <cfquery name="qryTest" datasource="DBTest"> 
       select * from emp_tab; 
     </cfquery> 

    <cfreturn selectRecordsResultSet /> 

</cffunction> 

如何使用cftry我處理DB例外?因爲這是返回查詢,是否有可能捕獲數據庫異常並將其傳遞到另一個頁面從它被稱爲?

感謝

回答

6

這是我一貫執行本示例:

<cffunction name="getCurrentRecordsCount" access="public" output="false" returntype="any" hint="Get total history records count"> 
    <cfargument name="filters" type="struct" required="false" default="#StructNew()#" hint="Filtering rules"> 
    <cfset var qGetRecordCount = "" /> 
    <cftry> 

     <cfquery datasource="#variables.dsn#" name="qGetRecordCount"> 
      SELECT COUNT(*) AS cnt FROM .... 
     </cfquery> 

     <cfreturn qGetRecordCount.cnt /> 

    <cfcatch type="any"> 
     <cfreturn error(cfcatch.message, cfcatch.detail) /> 
    </cfcatch> 
    </cftry> 
</cffunction> 

如果你只想處理數據庫錯誤,改變類型的數據庫

<cffunction name="error" access="private" output="false" returntype="boolean" hint="Set error status and message"> 
    <cfargument name="message" type="string" required="true" hint="Error message text" /> 
    <cfargument name="detail" type="string" required="false" default="" hint="Error detail text" /> 
    <cfset variables.fError = true /> 
    <cfset variables.fErrorText = arguments.message /> 
    <cfif Len(arguments.detail)> 
     <cfset variables.fErrorText = variables.fErrorText & " [" & arguments.detail & "]" /> 
    </cfif> 
    <cfreturn false /> 
</cffunction> 

<cffunction name="gotError" access="public" output="false" returntype="boolean" hint="Return latest error flag state"> 
    <cfreturn variables.fError /> 
</cffunction> 

<cffunction name="getError" access="public" output="false" returntype="string" hint="Return latest error text and reset the flag"> 
    <cfset var txt = variables.fErrorText /> 
    <cfset variables.fError = false /> 
    <cfset variables.fErrorText = "" /> 
    <cfreturn txt /> 
</cffunction> 

請注意,對於返回類型的方法=「作廢」我用CFSET代替cfreturn:

<cfset error(cfcatch.message, cfcatch.detail) /> 

所以在代碼中,我

錯誤處理和報告使用這三種方法進行可以做以下(CFSCRIPT):

// calculate filtered records count 
totalLogCount = request.loggingService.getCurrentRecordsCount(filters); 

// check if error was thrown 
if (request.loggingService.gotError()) { 
    // report the error details somehow 
    WriteOutput(request.loggingService.getError()); 
} 
+0

感謝謝爾蓋·Galashyn, 我得到了我在找的東西 – CFUser 2009-11-02 12:23:01