How to handle error for PHP cURL
<p>I've done every bit of tips and answers but I can't seem to find the right solution.</p>

<p>my cURL is as follows</p>

<pre><code>$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $curlIP."api/sparts/search/");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, "key=".$q."&amp;page=".$pg);
curl_setopt($curl, CURLOPT_FAILONERROR, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$data = curl_exec($curl);
curl_close ($curl);
</code></pre>

<p><strong>What does this do?</strong></p>

<p>It gets products data from a server where <code>$q</code> is the search key and <code>$pg</code> is the page number</p>

<p>This cURL works as intended assuming the server will always have an internet connection. As the developer we needed to have an error message whenever the cURL cannot connect to the server.</p>

<p><strong>What is the problem?</strong></p>

<p>For me to actually set an error message I need to know first if the error has happened. This where it gets weird for me. I tried to simulate connection failure by disabling the internet adapter of the server. </p>

<p>The result is:</p>

<p>the page stops parsing everything after the <code>$data = curl_exec($curl);</code>This includes the footer and everything after that line. I knew it because I tried to put echoes before and after <code>curl_exec</code> and it really stops there. therefore I cannot catch the error itself.</p>

<p><strong>What have I tried?</strong></p>

<p>I tried </p>

<ul>
<li>PHP <code>curl_error()</code> - which didn't really help since the script stops at <code>curl_exec</code></li>
<li>PHP <code>curl_errno()</code> - same</li>
<li>try and catch - This should have catch the error but it didn't which frustrates me even more.</li>
</ul>