在php异常中使用其他数据

时间:2014-03-01 11:07:38

标签: php exception exception-handling

我有执行python cgi的php代码,我想传递python跟踪(从cgi返回)作为额外数据到php异常我该怎么做?我怎样才能从catch(Exception e) {获得该值(它应该检查是否存在额外的值。)

我有这样的代码:

$response = json_decode(curl_exec($ch));
if (isset($response->error)) {
    // how to send $response->trace with exception.
    throw new Exception($response->error);
}
return $response->result;

我使用的json-rpc库应该将该数据返回给用户:

} catch (Exception $e) {
    //catch all exeption from user code
    $msg = $e->getMessage();
    echo response(null, $id, array("code"=>200, "message"=>$msg));
}

我是否需要编写新类型的异常,或者我可以使用普通Exception执行此操作吗?我想发送"data" =>

中抛出的所有内容

2 个答案:

答案 0 :(得分:11)

您需要扩展Exception类:     

class ResponseException extends Exception 
{
    private $_data = '';

    public function __construct($message, $data) 
    {
        $this->_data = $data;
        parent::__construct($message);
    }

    public function getData()
    {
        return $this->_data;
    }
}

投掷时:     

...
throw new ResponseException($response->error, $someData);
...

赶上时:

catch(ResponseException $e) {
    ...
    $data = $e->getData();
    ...
}

更新 - 动态物品属性(又名脏话)

当OP询问在不扩展Exception类的情况下执行此任务时,您可以完全跳过ResponseException类声明。我真的不建议这样做,除非你有充分的理由(有关详细信息,请参阅此主题:https://softwareengineering.stackexchange.com/questions/186439/is-declaring-fields-on-classes-actually-harmful-in-php

投掷部分:

...
$e = new Exception('Exception message');
$e->data = $customData; // we're creating object property on the fly
throw $e;
...

并且在捕捉时:

catch(Exception $e) {
    $data = $e->data; // Access data property
}

2018年9月编辑: 由于一些读者发现这个答案有用,我添加了另一个Stack Overflow问题的链接,该问题解释了使用动态声明的属性的缺点。

答案 1 :(得分:0)

当前,您的代码无需任何中间步骤即可将响应文本直接转换为对象。相反,您始终可以只保留序列化的(通过JSON)文本并将其附加到Exception消息的末尾。

$responseText = curl_exec($ch);
$response = json_decode($responseText);
if (isset($response->error)) {
    throw new Exception('Error when fetching resource. Response:'.$responseText);
}
return $response->result;

然后,您可以恢复错误日志中“ Response:”之后的所有内容,并可以反序列化或读取它。

顺便说一句,我也不会指望发送JSON的服务器,您应该确认响应文本实际上可解析为JSON,如果不是,则返回一个单独的错误。