Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在php中引发数组异常_Php_Exception Handling - Fatal编程技术网

如何在php中引发数组异常

如何在php中引发数组异常,php,exception-handling,Php,Exception Handling,所以我在一个文件中抛出了一条错误消息 $error_message = "Error received for " . $service . ": " . $_r['status'] . "\n" . "Message received: " . $_r['errors']; throw new My_Exception($error_message); 在另一个文件中我有 然而,问题是$\r['errors']是一个数组,它get$e->getMessage()只是将其打印为“数组”。如何修

所以我在一个文件中抛出了一条错误消息

$error_message = "Error received for " . $service . ": " . $_r['status'] . "\n" . "Message received: " . $_r['errors'];
throw new My_Exception($error_message);
在另一个文件中我有


然而,问题是$\r['errors']是一个数组,它get$e->getMessage()只是将其打印为“数组”。如何修改此代码以访问数组?

要将复杂的数据结构(如数组)转换为字符串(例如,对于错误消息),可以使用并将其第二个参数设置为
TRUE

... ": " . print_r($_r['status'], TRUE) . "\n" ...

问题是您试图将数组与字符串合并。结局总是这样

也许您应该向异常传递一个数组,以便以后可以使用它

<?php
class myException extends Exception {

    private $params;

    public function setParams(array $params) {
        $this->params = $params;
    }

    public function getParams() {
        return $this->params;
    }
}

// later it can be used like this:
try {
    $exception = new myException('Error!');
    $exception->setParams(array('status' => 1, 'errors' => array());

    throw $exception;
}
catch (myException $e) {
    // ...
}
?>

所以您的示例代码有点糟糕,但是假设

$_r['errors'] = array(
    'Message 1',
    'Message 2',
    'Message 3',
    'Message 4',
    'Message 5',
);
然后

关键是获取错误消息数组,并用换行符(或其他任何形式)将它们连接在一起

但是我有点同意你的评论,你可能使用了错误的异常框架。你能发布你想做的事情吗


一般的经验法则是为每个唯一的事件抛出一个异常。您不会收集一堆错误消息,然后立即将它们全部抛出。

我们可以使用json格式

   throw new Exception(json_encode(['type'=>'error','isExit'=>'true','title'=>'SystemConfigError']));
而且在捕获中

        catch (Exception $error)
    {
        var_dump(json_decode($error->getMessage(),JSON_OBJECT_AS_ARRAY));
    }

这是一种糟糕的形式,因为它破坏了异常的基本接口。如果您需要传递一些值,只需添加一个收集和存储它们的方法。+1完美。现在,该对象正在获得而不是失去功能。
   throw new Exception(json_encode(['type'=>'error','isExit'=>'true','title'=>'SystemConfigError']));
        catch (Exception $error)
    {
        var_dump(json_decode($error->getMessage(),JSON_OBJECT_AS_ARRAY));
    }