Ted pottel
Ted pottel

Reputation: 6983

Catching errors database errors in ColdFusion

I have a ColdFusion cfm file that communicates with a sql server database. Right now if something goes wrong with the database connection, it brings up an error page generated by ColdFusion. Is there a way I can catch the errors and display a message like, "Database server temporarily down, please come back later"? Ted

Upvotes: 1

Views: 5597

Answers (1)

Jake Feasel
Jake Feasel

Reputation: 16955

You can use try/catch for an individual query - this will be the most granular approach.

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

You can also use the cferror tag for global exception handling (put this in Application.cfm):

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

You can also use onError method within Application.cfc, which will also (like the cferror tag) catch all errors that occur during the request:

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

Upvotes: 7

Related Questions