如何捕获异常并发送自定义错误消息

时间:2019-08-07 14:27:08

标签: php laravel

我有一个功能

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();
    }
}

我像这样使用这个功能:

$obj = new ZohoV2();

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

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

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

这些功能使我可以从CRM的数据库中检索用户。

但是当用户不存在时,他向我发送了500错误。

{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: [{,…}, {,…}, {,…}, {,…}, {,…}, {,…},…]

如何拦截此错误,以便我可以根据需要进行处理并发送错误消息?

谢谢

1 个答案:

答案 0 :(得分:1)

从您的第一个代码块中删除try / catch

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

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

        $candidates = $response->getResponseJSON();

        return $candidates;
}

并将其移动到第二个代码块(我假设它是控制器)

$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);