I am almost done making a web app with CFML but I have a question on handling errors. For example, a part of my web app can execute user entered SQL code. However if the SQL code the user provides isn't valid then it will not execute properly and I get an error like this: https://devintranet.dep.gov/oogns/sharedComponents.cfc 500
Which makes sense. If it helps answering my question at all here is the information on the network tab:
All I want is to be able to catch when the status code returns 500 and be able to take action based on that. For example if I make a request that ends up having a status code of 500 then I can use JS alert to tell the user something went wrong.
Here is the function in sharedComponents.cfc:
<cffunction name="LoadAttribute" access="remote" returnformat="plain" returntype="string" >
<cftry>
<cfquery name ="AttributeQuery" datasource="RBDMS_UPDATE">
SELECT *
FROM dbo.OOGNS_Queries
WHERE UPPER(QueryName) = UPPER(<cfqueryparam cfsqltype="varchar" value="#form.default_ProfileName#" />)
</cfquery>
<cfcatch>
<cfoutput>
#cfcatch.Detail#<br />
#cfcatch.Message#<br />
#cfcatch.tagcontext[1].line#:#cfcatch.tagcontext[1].template#
</cfoutput>
</cfcatch>
</cftry>
<cfreturn AttributeQuery["#default_ColName#"][1] />
</cffunction>
And here is the ajax function that calls it:
$.ajax({
type: "POST",
url: "sharedComponents.cfc",
data: { method: "LoadAttribute",
default_ProfileName: ProfileName,
default_Entity: Entity,
default_ColName: ColName,
},
datatype: "json"
}).done(function(returnresult) {
There is actually a lot of code after that but I believe it to be irrelavent to what I'm trying to do. Literally if you can show me how to obtain the status code from the response header I think I'll be good.
There are two separate issues in your request.
Catch errors on server side
It can be that the requested column is not available in the AttributeQuery
result. So you have to check for that before accessing it.
One way to do this is:
<cfreturn structKeyExists(AttributeQuery, default_ColName) ?
AttributeQuery[default_ColName] : "" />
Catch errors on client side
To catch HTTP errors you can use the error()
function jQuery's ajax()
function provides, as Miguel-F and AndreasRu mention in their comments.