Pergunta

Eu tenho uma função no arquivo de CFC, que será chamado a partir do arquivo .cfm como abaixo

 <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>

Como posso lidar com DB exceção usando CFTRY? como este está retornando Query, é possível capturar a exceção DB e passar o Detalhes para a outra página de onde é chamado?

Graças

Foi útil?

Solução

Aqui está um exemplo de minha implementação habitual deste:

<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>

Se você quiser tratar erros único banco de dados, tipo de alteração no banco de dados .

Manipulação de erros e relatórios realizada utilizando esses três métodos:

<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>

Por favor note que para métodos com returntype = "vazio" Eu uso cfset vez de cfreturn:

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

Assim, no código que pode fazer o seguinte (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());
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top