首页 > 解决方案 > 如何捕获异常并发送自定义错误消息

问题描述

我有一个功能

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

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

谢谢

标签: phplaravel

解决方案


从您的第一个代码块中删除 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);

推荐阅读