Eric Belair
Eric Belair

Reputation: 10682

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....

Upvotes: 1

Views: 1181

Answers (2)

Alex
Alex

Reputation: 7833

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#");
}

Upvotes: 4

James A Mohler
James A Mohler

Reputation: 11120

More of a comment, but this is way too long. Just do a dump off whatever exception is happening. Then filter on the specific exception

public void function tryRequest() {
    try {
        makeRequest();
    }
    catch(any e) {
        writedump(e);
        // then find the details on the specific exception type
    }
}

Upvotes: 0

Related Questions