How to Use CFAbort to Halt Page Processing in CFML
In this tutorial, you'll discover the full functionality of the cfabort
tag in CFML. This tag is commonly used to halt page processing at the tag's location when certain conditions occur with the conditional logic.
The Syntax
The
showError
- The error message to display when page processing has aborted. This message will display using the standard CFML error page.type
- Defines the abort type. request aborts the request in its entirety, and is the default value. page aborts the current page execution.
<cfabort [showError=string [type=string]]>
Code Examples
Let's walk through a few code examples to illustrate how this tag works.
Abort with no parameters
First, we'll create two strings, Foo and Bar. The cfabort
tag will be placed between the two words, stopping page execution halfway through and displaying only "Foo" on the screen:
Foo
<cfabort>
Bar
Abort and throw an error
Another example is to abort page processing and display a custom error message on the screen:
Foo
<cfabort showError="An error has occurred.">
Bar
Abort in a loop
In this example, we'll abort page processing halfway through a loop:
<cfloop index="i" from="1" to="5">
<cfif i eq 4>
Aborted.
<cfabort>
</cfif>
<cfoutput>#i#</cfoutput>
</cfloop>
The resulting output for this example is:
1 2 3 Aborted.
Abort when an error occurs
And, in this example, we'll abort after deliberately calling a non-existing function. An error will be thrown and page processing will stop immediately:
<cftry>
<cfset variables.id = getUserID()>
<cfcatch type="any">
<cfdump var="#cfcatch#">
<cfabort>
</cfcatch>
</cftry>
Script Syntax
A similar example in script syntax can be accomplished like this:
<cfscript>
try {
variables.id = getUserID();
catch(any error) {
writeDump(error);
abort;
}
}
</cfscript>
Conclusion
As you can see, the
Created: July 18, 2023
Comments
There are no comments yet. Start the conversation!