在php例外中使用其他数据 我有执行Python CGI的PHP代码,我想通过Python Trace(从CGI返回)作为额外数据返回到PHP例外,我该如何执行此操作,以及如何从catch(异常E){(IT)获得该值

问题描述 投票:0回答:1
$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" =>

    

您需要扩展异常类:

<?php

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

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

    public function getData(): string
    {
        return $this->_data;
    }
}
throw时:

<?php ... throw new ResponseException($response->error, $someData); ...
php exception
1个回答
39
投票
捕捉时:

catch(ResponseException $e) { ... $data = $e->getData(); ... }
动态属性(不建议)

please
注释
,这将导致php 8.2中的折旧错误,并根据php rfc rfc

Https://wiki.php.net/rfc/rfc/deprecate/deprecate_dynamic_properties

当OP询问执行此任务的情况下,而无需扩展
Exception

课,您可以完全跳过

ResponseException

类声明。我真的不建议这样做,除非您有很大的理由(有关更多详细信息,请参见此主题:Https://softwareengineering.stackexchange.com/questions/questions/186439/is-declaring-fields-on-clields-on-classes-classes-classes-classes-classes-实际上是在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月编辑:
正如一些读者发现此答案有用的那样,我添加了一个指向另一个堆栈溢出问题的链接,该问题解释了使用动态声明的属性的不利之处。
    

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

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

然后您可以在“响应:”中恢复所有内容:在您的错误日志中,并可以选择地进行序列化或读取它。
除了一个,我也不会依靠发送JSON的服务器,您应该验证响应文本实际上是可以解析为JSON的,并为此返回单独的错误。
    

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.