如何从CFC文件中获取异常详细信息

时间:2009-11-02 08:41:48

标签: exception-handling coldfusion cfc

我在CFC文件中有一个函数,它将从.cfm文件中调用,如下所示

 <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处理数据库异常?因为这是返回Query,是否可以捕获数据库异常并将详细信息传递给调用它的其他页面?

由于

1 个答案:

答案 0 :(得分: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>

请注意,对于使用returntype =“void”的方法,我使用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());
}