Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ixudra's avatar

Catching errors in cURL requests

Question about cURL: say I have the following code

class MyController {

    public function index()
    {
        throw new \InvalidArgumentException('You shall not pass!!');
    }
}

Now let's say that I want to call this piece of code via cURL:

// Create a curl handle to a non-existing location
$ch = curl_init('http://someUrl.net/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

if(curl_exec($ch) === false)
{
    echo curl_error($ch);
}

// Close handle
curl_close($ch);

The code itself works fine, only I don't see my custom exception message. All I see is error code 500 and the following error message:

The requested URL returned error: 500 Internal Server Error

This message is not very helpful as I want to see what exactly went wrong. Is there a way to do this?

0 likes
3 replies
ejdelmonico's avatar

Maybe something like this

if(curl_error($e))
{
    echo 'error:' . curl_error($e);
}

If you want to use custom messages then use errno to get the 500 and then check for whatever error to send a custom message. Or, you could do it in a try/catch and throw an exception.

if(curl_errno($ch))
{
      throw new Exception(curl_error($ch));
}
ixudra's avatar

@jekinney Try-catch will not work as controller and cURL request are in two different applications. My question is related to recovering the error message in the second application, where no actual exception is thrown. Also your condescending tone is noted but not appreciated

@ejdelmonico As you can see from my example, using curl_error($e); returns a generic error message instead of the You shall not pass that I expect. Maybe there is something wrong with my cURL request, but in all my experiments, I have never been able to make this work.

Please or to participate in this conversation.