捕获错误ColdFusion中的数据库错误



我有一个ColdFusion cfm文件,它与sql server数据库通信。现在,如果数据库连接出现问题,就会显示ColdFusion生成的错误页面。有没有一种方法可以捕捉错误并显示类似"数据库服务器暂时关闭,请稍后返回"的消息?Ted

您可以对单个查询使用try/catch,这将是最精细的方法。

<cftry>
  <cfquery datasource="myDSN">BROKEN SQL</cfquery>
  <cfcatch type="database">
    <h1>Database Offline!</h1>
    <p>Sorry, the database threw an error: #cfcatch.queryError#.  Try again later.</p><cfabort>
  </cfcatch>
</cftry>

您还可以使用cferror标记进行全局异常处理(将其放在Application.cfm中):

<cferror 
  type="exception" 
  exception="database" 
  template="myFriendlyDatabaseErrorTemplate.cfm">

您也可以在Application.cfc中使用onError方法,它也会(像cferror标记一样)捕获请求期间发生的所有错误:

<cffunction name="onError" returnType="void">
    <cfargument name="Exception" required=true/>
    <cfargument name="EventName" type="String" required=true/>
    <cfif arguments.Exception IS "database">
      <cfinclude template="myFriendlyDatabaseErrorTemplate.cfm">
    </cfif>
</cffunction>

最新更新