Jeremy
Jeremy

Reputation: 206

How to catch exception and send custom error message

I have a function

public function getCandidates($candidateEmail)
{
    try {
        $moduleIns = ZCRMRestClient::getInstance()->getModuleInstance('Candidats');

        $response   = $moduleIns->searchRecordsByEmail($candidateEmail, 1, 1);

        $candidates = $response->getResponseJSON();

        return $candidates;

    } catch (ZCRMException $e) {
        echo $e->getMessage();
        echo $e->getExceptionCode();
        echo $e->getCode();
    }
}

And I use this function like that :

$obj = new ZohoV2();

$response = $obj->getCandidates($request->email);

$candidate = $response['data'][0];

return response()->json([ 'status' => 'success', 'candidate' => $candidate ], 200);

Theses functions allows me to retrieve a user from a database of a CRM.

But when the user does not exist, he sends me a 500 error.

{message: "No Content", exception: "zcrmsdk\crm\exception\ZCRMException",…}
exception: "zcrmsdk\crm\exception\ZCRMException"
file: "/home/vagrant/CloudStation/knok/myath/myath-app/vendor/zohocrm/php-sdk/src/crm/api/response/BulkAPIResponse.php"
line: 61
message: "No Content"
trace: [{,…}, {,…}, {,…}, {,…}, {,…}, {,…},…]

How to intercept this error so that I can process it as I want and send an error message ?

Thank you

Upvotes: 1

Views: 303

Answers (1)

PtrTon
PtrTon

Reputation: 3835

Remove the try/catch from your first code block

public function getCandidates($candidateEmail)
{
        $moduleIns = ZCRMRestClient::getInstance()->getModuleInstance('Candidats');

        $response   = $moduleIns->searchRecordsByEmail($candidateEmail, 1, 1);

        $candidates = $response->getResponseJSON();

        return $candidates;
}

And move it to the second code block (I assume it's the controller)

$obj = new ZohoV2();

try {
   $response = $obj->getCandidates($request->email);
} catch (ZCRMException $e) {
   return response()->json(['status' => 'failed', 'error' => $e->getMessage()], 404);
}

$candidate = $response['data'][0];

return response()->json([ 'status' => 'success', 'candidate' => $candidate ], 200);

Upvotes: 1

Related Questions