CodeIgniter Forums
curlrequest error handling - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: curlrequest error handling (/showthread.php?tid=79438)



curlrequest error handling - chakycool - 06-16-2021

Hi,
I got the "curlrequest" service working just fine but if there is an error such as a invalid login which ends in a 400 Bad request I get a codeignitor error "CodeIgniter\HTTP\Exceptions\HTTPException". How can I get this error to the response other than getting a cogeigniter error.


RE: curlrequest error handling - includebeer - 06-17-2021

Use a try/catch to catch the exception.


RE: curlrequest error handling - chakycool - 06-19-2021

Didn't work includebeer Sad
I Still get the same error on a 400 response.

CodeIgniter\HTTP\Exceptions\HTTPException
22 : The requested URL returned error: 400

SYSTEMPATH\HTTP\CURLRequest.php at line 796


RE: curlrequest error handling - includebeer - 06-19-2021

What do you mean by “didn’t work”?
Show your code and the error message if any…

Here’s an example how to use try/catch: http://codeigniter.com/user_guide/general/errors.html?highlight=catch


RE: curlrequest error handling - chakycool - 06-19-2021

try {
$response = $this->getToken($keys);
print_r($response);
}

catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}


private function getToken($data){

$body = '{"username":"[email protected]","password" : "'.$data->pw.'"}';
$client = \Config\Services::curlrequest();
$result = $client->setBody($body)->request('post', $data->url.'/v1/login/', [
'headers' => [
'Content-Type' => 'application/json',
'x-api-key' => $data->key
]
]);
return json_decode($result->getBody());
}

Sorry I didn't share the code before. Now on the code above I'm passing a invalid email and I end up with an error (CodeIgniter\HTTP\Exceptions\HTTPException).
If all is good no errors.

I found the problem

Add the "\" to "Exception" making it " \Exception"

Thank you so much incluebeer.


RE: curlrequest error handling - includebeer - 06-20-2021

Glad it's working now ! Namespaces can be tricky !  Cool