I am trying to write an if statement in Coldfusion 16 to check to see if it can connect to the database or that it exists. If it can connect to the database then show the page otherwise show down for maintenance. How should I just check to make sure the database is up? Any help with this would be greatly appreciated.
<cfquery name="DBUP" datasource="datasource">
SELECT ID
FROM dbo.Entry
</cfquery>
<cfif DBUP>
Show Page
<cfelse>
Show Down For Maintenance
</cfif>
You shouldn't directly put a error message or file in a catch statement. We should check one more condition ie) Error code is 0 or not. Imagine in some time the developer may give wrong query like undefined column or missing syntax etc... In that time also the catch will executed. So as per the requirement we have to check the datasource exists or not. If we want to check all type of issue means we no need of the error code conditions.
<cftry>
<cfset showPage = true>
<cfquery name="DBUP" datasource="datasource">
SELECT ID FROM dbo.Entry
</cfquery>
<cfcatch type="database">
<!--- The error code 0 is mentioned Datasource could not be found/exits. --->
<cfif cfcatch.cause.errorcode eq 0 >
<cfset showPage = false >
<!--- Data source does not exists --->
</cfif>
</cfcatch>
</cftry>
Based on showPage value do you business logic here
....
....
....
You will need to add it in Application.cfc onRequest method probably.
<cftry>
<cfquery name="DBUP" datasource="datasource">
SELECT ID
FROM dbo.Entry
</cfquery>
<cfcatch type="any">
Show DOwn For Maintenance
<!---everything optional below this line--->
<!---can show some custom message--->
<cfinclude template="errorMsg.cfm">
<!---stop the processing further--->
<cfabort>
</cfcatch>
</cftry>
Related
I kept getting the "Error in custom script module" when checking if the session variable is set or not in my details page. Even if the session variable not set, wasn't this statement supposed to give me either true or false instead of error out?
<cfif StructKeyExists(session.mysiteShibboleth, "isAuthenticated") and (session.mysiteShibboleth.isAuthenticated) >
<cflog text="Session-Defined-5: isAuthenticated" type="Information" file="Authentication">
<cfelse>
<cflog text="Session-Defined-7: It's not authenticated'" type="Information" file="Authentication">
</cfif>
In my authenticate.cfm file, this is where the session variables are set.
<cfif cgiReferer eq shibboleth_url>
<cfscript>
session.mysiteShibboleth = StructNew();
session.mysiteShibboleth.username=REReplace(http_header.headers.eppn, "#mysite.com","","ALL");
session.mysiteShibboleth.mail=http_header.headers.eppn;
session.mysiteShibboleth.groups=ArrayToList(REMatch('WEB\.[A-Z.-]+', http_header.headers.member));
session.mysiteShibboleth.isAuthenticated="true";
</cfscript>
</cfif>
I have also tried the following and it's still error out. I have read this thread and it doesn't seem to resolve my issue.
<cfif IsDefined("session.mysitecShibboleth.isAuthenticated")>
You need to make sure that session.mysiteShibboleth exists before you check for a key on mysiteShibboleth. That is likely the source of your problem, but if you gave us the actual error message received, we could help you better.
Also, note that <cfif IsDefined("session.mysitecShibboleth.isAuthenticated")> has an errant c in the variable name.
** Edit: Adding code example
<cfif StructKeyExists(session, "mysiteShibboleth">
<cfif StructKeyExists(session.mysiteShibboleth, "isAuthenticated") and (session.mysiteShibboleth.isAuthenticated) >
. . .
</cfif>
<cfelse>
. . .
</cfif>
I am severely new to ColdFusion... I have searched for help on this statement and have found a bunch of material, but still don't understand what is going on. All of the parts of this statement make sense, but when I put them all together, it's confusing... the ColdFusion 8: IsDefined("URL.variable) and is not"" thread is the closest, but I still don't understand. This is the 1st statement in the index.cfm file of my application. It's not throwing an error, I just want to understand how it works. Thank you.
I have yet to be able to successfully post code here, so here is a link to a text version of the index.cfm.
Edit:
The code below should be the relevant sections related to URL.openFile
<cfif isdefined("URL.openFile")>
<cfquery name="getFile" datasource="xxxxxxxx">
SELECT filename, filename2, filecontent, filesize
FROM Help_FooterInfo
WHERE Help_id=5 and Section='Registration'
</cfquery>
<cfset sproot=#getDirectoryFromPath(getTemplatePath())#>
<cfset newDest = #sproot#&"temp\">
<cfoutput query="getFile">
<cfheader name="Content-Disposition" value="attachment; filename=#getfile.FileName2#">
<cfcontent type="application/msword" variable="#getfile.filecontent#">
</cfoutput>
</cfif>
...
<cfquery name="getRegistration" datasource="xxxxxxxx">
select * from help_footerinfo where help_id=5
</cfquery>
....
<cfoutput>#getRegistration.Content#</cfoutput><br>
<a href="<cfif #getRegistration.filename2# neq "">index.cfm?openfile=Yes</cfif>" target="_blank">
<u><cfoutput>#getRegistration.FileName#</cfoutput></u>
</a>
The error message I am receiving (see comment below): ORA-00942: table or view does not exist (ColdFusion application)
This:
<cfif IsDefined("URL.variable") and URL.variable is not "" >
means, "If url.variable actually exists and is not an empty string".
A better alternative for isDefined("URL.variable") is StructKeyExists(url,"variable").
Other alternatives for is not "" include len(trim(url.variable)) gt 0, and isNumeric(url.variable).
I'm using Coldfusion Fusebox 3 and I would like to know how I can keep my app from throwing an error message if someone thoughtlessly removes the Circuit and fuseaction from the URL.
For example, if the original URL is:
http://www.noname/Intranet/index.cfm?fuseaction=Bulletins.main
...and someone removes the circuit information so it reads like the following: http://www.noname/Intranet/index.cfm?fuseaction=
...the app throws an error message. Can I code against something like this happening?
Here is my fbx_Settings.cfm file as it exists right now. Thank you.
Try something along these lines, haven't had chance to test but should go something like this in your index.cfm file.
<cfprocessingdirective suppressWhiteSpace="yes">
<cftry>
<!--- Include the config file --->
<cfinclude template="../config.cfm">
<cfset variables.fromFusebox = True>
<cfinclude template="fbx_fusebox30_CF50.cfm">
<cfif Len(fusebox.fuseaction) EQ 0>
<!--- Error Handle --->
</cfif>
<cfcatch type="Any">
<!---<cfset SendErrorEmail("Error", cfcatch)><cfabort />--->
</cfcatch>
</cftry>
</cfprocessingdirective>
or better still, in your switch file have a default case such as:
<cfdefaultcase>
<cfinclude template="act_HandleError.cfm">
<cflocation url="hompage.cfm" addtoken="false">
</cfdefaultcase>
Hope this helps!
Currently working with Coldfusion 10 and cfsearch.
After many hours of trial and error, I have managed to get cfindex to collect all my custom field data so that it is available to me as fields for the output on my search results page.
My only issue now, is that the search will be able to search for things like true / false strings and it will return in the search results.
I could run a QoQ to strip those out, im just wondering if anyone has any suggestions for adding fields to an index but not having them searchable.
Any ideas greatly appreciated
my current code is below
<cftry>
<!-- create new searchable collection -->
<!--- cfcollection action= "create" collection="testsearch" path= "#expandPath('/assets/scripts/server/solr/')#" ---->
<cfcollection action= "list" name="collectionlist">
<cfdump var="#collectionlist#">
<cfquery name="MyQuery" datasource="#request.DSN#" maxrows="10">
SELECT *
FROM Store_products
</cfquery>
<cfdump var="#myQuery#">
<cfset myAttr = structNew()>
<cfset variables.columns = "COST,CREATEDDATE,CUSTOM_MESSAGE,CUSTOM_MESSAGE_LENGTH,DISPLAYNAME,DONTINCLUDEINSTOCKUPDATE,FEATUREDPRODUCT,FINALDAYS,FREEDELIVERY,HEIGHT,HTMLMETADESCRIPTION,HTMLMETAKEYWORDS,IMAGE1,IMAGE10,IMAGE2,IMAGE3,IMAGE4,IMAGE5,IMAGE6,IMAGE7,IMAGE8,IMAGE9,ISBUNDLE,ISNEWPRODUCT,ISONLINE,ISONSALE,ISSILENT,LONGDESCRIPTION,MANUFACTURER,NOVOUCHERS,ONLINEEXCLUSIVE,PARTNUMBER,PRICE,PRICELEVEL1,PRICELEVEL10,PRICELEVEL11,PRICELEVEL12,PRICELEVEL13,PRICELEVEL14,PRICELEVEL15,PRICELEVEL2,PRICELEVEL3,PRICELEVEL4,PRICELEVEL5,PRICELEVEL6,PRICELEVEL7,PRICELEVEL8,PRICELEVEL9,PRODUCTCATEGORY,PRODUCTCOLOR,PRODUCTMATERIAL,PRODUCTNAME,PRODUCTSIZE,PRODUCTSTYLE,PRODUCTTITLE,PRODUCTVIEWS,RRP,SALEEND,SALEPRICE,SALESTART,SHORTDESCRIPTION,SOLDOUT,STOCKQUANTITY,STORESORTORDER,TAXEXEMPT,VOLUME,WEIGHT,WIDTH">
<cfloop from="1" to="#ListLen(variables.columns,',')#" index="idx">
<cfset myAttr[listGetAt(variables.columns,idx,',') & "_s"] = listGetAt(variables.columns,idx,',') >
</cfloop>
<cfindex attributecollection="#myAttr#" action="update" collection="testsearch" type="custom" body="DISPLAYNAME,HTMLMETADESCRIPTION,HTMLMETAKEYWORDS,LONGDESCRIPTION,MANUFACTURER,PARTNUMBER,PRODUCTNAME,PRODUCTTITLE,RRP,SHORTDESCRIPTION" query="MyQuery" key= "productname">
<cfsearch name="searchResults" collection="testsearch" criteria="false" >
<cfdump var="#searchResults#">
<cfcatch type="any">
<cfdump var="#cfcatch#">
</cfcatch>
</cftry>
I have a form where I can upload logos a plenty. I'm validating files (empty form fields, wrong extension, ...) inside a cftry/cfcatch statement.
When I find an error in the cftry, I do this:
<cfthrow type="FileNotFound" message="#tx_settings_app_error_create_first#" />
and inside my 'cfcatch'
<cfcatch>
<cfoutput><script type="text/javascript">window.onload = function(){alert("#cfcatch.message#");window.location.href="hs_apps.cfm"; } </script></cfoutput>
</cfcatch>
This works fine, catches all errors and alerts the user what is wrong.
Now I wanted to use the same handler on a database call where I'm checking for duplicate username. Still the same:
<cfquery datasource="#Session.datasource#" name="duplicates">
SELECT a.app_alias
FROM apps AS a
WHERE a.iln = <cfqueryparam value = "#Session.loginID#" cfsqltype="cf_sql_varchar" maxlength="13">
AND a.app_alias = <cfqueryparam value = "#form.app_basic_alias#" cfsqltype="cf_sql_varchar" maxlength="50">
</cfquery>
<cfif duplicates.recordcount GT 0>
<cfthrow type="FileNotFound" message="#tx_settings_apps_error_dup#" />
</cfif>
The cfcatch is also the same.
However. This now procudes a server error page and I'm thrown out of the application.
Question:
Any idea, why I'm struggling to get cftry/cfcatch to work here? I'm clueless.
Thanks!
EDIT:
Here is the full code
<cfif isDefined("send_basic")>
<cfset variables.timestamp = now()>
<cfset variables.orderview = "1">
<cfif form.send_basic_type EQ "new">
<cftry>
<cfif module_check.recordcount GT 0>
<cfloop query="module_check">
<cfif module_check.module_name EQ "preorder">
<cfset variables.module_name = module_check.module_name>
<cfset variables.b2b_preord_ok = "true">
</cfif>
</cfloop>
<cfif form.app_basic_orderview EQ "preo">
<cfset variables.orderview = "0">
</cfif>
</cfif>
<!--- PROBLEM HERE: DUPLICATES --->
<cfquery datasource="#Session.datasource#" name="duplicates">
SELECT a.app_alias
FROM apps AS a
WHERE a.iln = <cfqueryparam value = "#Session.loginID#" cfsqltype="cf_sql_varchar" maxlength="13">
AND a.app_alias = <cfqueryparam value = "#form.app_basic_alias#" cfsqltype="cf_sql_varchar" maxlength="50">
</cfquery>
<cfif duplicates.recordcount GT 0>
<cfthrow type="FileNotFound" message="#tx_settings_apps_error_dup#" />
</cfif>
<!--- IF PASS, CREATE/UPDATE --->
<cfquery datasource="#Session.datasource#">
INSERT INTO apps ( ... )
VALUES( ... )
</cfquery>
<cfset variables.app_action = "Applikation erstellt">
<!--- success --->
<cfoutput><script type="text/javascript">window.onload = function(){alert("#tx_settings_app_cfm_create#");}</script></cfoutput>
<cfcatch>
<cfoutput><script type="text/javascript">window.onload = function(){alert("#tx_settings_app_err_create#");}</script></cfoutput>
</cfcatch>
</cftry>
<cfelse>
<cftry>
<!--- UPDATE --->
<cfquery datasource="#Session.datasource#">
UPDATE apps
SET ... = ...
</cfquery>
<cfset variables.app_action = "Applikation aktualisiert">
<!--- success --->
<cfoutput><script type="text/javascript">window.onload = function(){alert("#tx_settings_app_cfm_update#");}</script></cfoutput>
<cfcatch>
<cfoutput><script type="text/javascript">window.onload = function(){alert("#tx_settings_app_err_update#");}</script></cfoutput>
</cfcatch>
</cftry>
</cfif>
</cfif>
The error message I'm getting it the message I specify =
<cfthrow type="FileNotFound" message="#tx_settings_apps_error_dup#" />
Which if caught should alert the text behind tx_settings_apps_error_dup. If I dump the cfcatch, cfcatch.message is my specified text, so the error gets caught allright, only I get a server error page vs. an alert. I'm using exactly the same handler for fileuploads and form submits. I don't get why it's not working here?
Thanks for helping out!
WORKAROUD:
Note nice, but suffice(s):
<cfif dups.recordcount NEQ 0>
<cfoutput><script type="text/javascript">window.onload = function(){alert("#tx_settings_apps_error_dup#"); location.href = "hs_apps_detail.cfm?create=newApp&id=none";}</script
</cfoutput>
<cfabort>
</cfif>
So when a duplicate is found I alert the user, reload the exact same page and cfabort to prevent the old page from processing further. Patch that is.
(moved this down from being just a comment)
OK, so the catch is definitely catching the exception if you're able to dump it, so it's not that the try/catch ain't working, it's something else. Bear in mind that processing will continue until the end of the request after your catch block, and only then will the output buffer be flushed, and your alert() sent to the browser. It sounds to me like after your output the alert, and processing continues, some OTHER error is occurring which is causing the server's error page to display. I recommend getting rid of the error page temporarily and eyeballing the actual error CF is raising.
NB: if you want processing to stop immediately in the catch block after you output the alert(), you're going to need to tell CF that, ie: with a <cfabort>. Otherwise, as per above, it'll just keep going.
I think exceptions that are caught by the server error page are still logged in the exception log, but I could be wrong. You could always put an onError() handler in your Application.cfc, log whatever error occurred, then rethrow the error so the error page still deals with it. That way you get the info on the error, and the punter still sees the nice error page.