Coldfusion try/catch example.
Like other languages, Coldfusion has the ability to attempt code and then provide a custom error if it fails. This is good if you cannot test your code and example would be if you are waiting for other groups to get database development done, or server environment constraints.
So here is a simple example.
Say I have a query that adds favorites to my table first I am going to set some simple variables
<cfset me = "Frank">
<cfset myFav = "Franklin">
Next, I am going to set up my try/catch code Note I have a primary key made up of fvrt_src, fvrt_sel, meaning I cannot add it twice and if I refresh the screen the error will be produced.
<cftry>
<cfquery
datasource="#request.dsn#"
name="addingToFav">
insert into favorites (fvrt_src, fvrt_sel)
values ('#me#', '#myfav#')
</cfquery>
If the error is produced the catch will sense the database error and produce a nice controlled session error instead of a screen with gibberish (client confusion screens).
<cfcatch type="database">
<cfset session.favAddError = "User has already been added to your favorties<br>
please check your favorites list above.">
</cfcatch>
</cftry>
Next if the session has been created I display the error message below.
<cfif isdefined(“session.favAddError”)>
<cfoutput>
#session.favAddError#
</cfoutput>

0 Comments:
Post a Comment
Links to this post:
Create a Link
<< Home