Not yet rated

Problem

An application needs to be able to throw a custom error when a problem occurs.

Solution

ColdFusion allows an application to throw a custom error using the <cfthrow> tag.

Detailed explanation

There are times when an application needs to throw an error when an actual error has not occured.  For example, an application that allows users to register and requires a unique username or unique email address will want to throw an error if a user attempts to register with a username or email address that is already in use. This is accomplished by using the <cfthrow> tag.

The <cfthrow> tag allows you to specify the custom attributes detail, errorCode, extendedInfo, message, object and type. All of these attributes are optional with the type attribute defaulting to Application.

The code below illustrates a solution to the problem above, where a unique email address is required.  If the email address is not unique ColdFusion will throw an error message with a custom message and type.

<cffunction name="checkEmailAddress" access="public"
returntype="boolean">
<cfargument name="emailAddress" required="true" type="string"
/>
<cfquery datasource="#request.dsn#"
name="qCheckEmailAddress">
SELECT 
emailAddress
FROM
tbl_User
WHERE
emailAddress = <cfqueryparam value="#arguments.emailAddress#"
cfsqltype="cf_sql_varchar" />
</cfquery>

<!--- check to see if any records matched, if there was a match,
throw an error --->
<cfif qCheckEmailAddress.RecordCount>
<cfthrow type="UNIQUE_VIOLATION" message="Email address is not
unique." />
<cfelse>
<cfreturn true />
</cfif>
</cffunction>

If the user submits a non-unique email and the error is not caught, the following will appear:

 

An application needs to be able to throw a custom error when a problem occurs.

In order to catch the exception the <cfcatch> tag must specify the custom type that has been throw in the type attribute.

<cfcatch type="UNIQUE_VIOLATION">

The email address supplied is not unique

</cfcatch>

The <cfthrow> tag gives the application the ability to handle custom errors without problems and is yet another excellent and easy to use tool supplied by ColdFusion.

 


+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes