coldfusiontry-catchcfmlcoldfusion-11timeoutexception

How to catch a ColdFusion CFHTTP timeout exception?


I have a page where I make a remote request to an external API. I sometimes get request timeouts when making the request, so, my plan to set a timeout in the CFHTTP tag that is lower than my default requesttimeout setting and catch it. However, I can't get my CFTRY/CFCATCH to catch it. Here is my pseudo code:

private void function makeRequest(){
        cfhttp(
            url="https://api.somesite.com/",
            method="POST",
            timeout="1",
            throwonerror="true",
            result="LOCAL.ApiHttpResult"
            ) {
        ...
        }
}

public void function tryRequest() {
    try {
        makeRequest();
    }
    catch(coldfusion.runtime.RequestTimeoutException e) {
        abort;
    }
}

I get the same result out of CFSCRIPT:

<cffunction access="public" returntype="void" name="tryRequest">
    <cftry>
        <cfscript>
            makeRequest();
        </cfscript>
    <cfcatch type="coldfusion.runtime.RequestTimeoutException">
        <cfabort />
    </cfcatch>
</cffunction>

Is there something special about the CFHTTP timing out that makes this impossible to catch programmatically? Any ideas on how to do this?

Thanks....


Solution

  • You just misspelled the exception type: It's coldfusion.runtime.RequestTimedOutException (coldfusion.runtime.RequestTimedOutException).

    But there's another way to do this without exception handling. Just do a regular cfhttp, but don't specify the throwOnError attribute (or keep it false). This will still return a response struct after the request has timed out. It will be populated with status code 408 Request Time-out. You can access it like this:

    if (left(LOCAL.ApiHttpResult.Statuscode, 3) eq "408") {
        writeOutput("HTTP request timed out");
    } else {
        writeOutput("HTTP request successful with status: #LOCAL.ApiHttpResult.Statuscode#");
    }