我正在使用这样的数组抛出异常:
$response = array('login_email' => '<div class="warning">Your email and / or password were incorrect</div>');
throw new \Exception($response);
我正在抓的是:
Error: Wrong parameters for Exception([string $exception [, long $code [, Exception $previous = NULL]]])
有什么想法吗?
答案 0 :(得分:12)
Exception()不会占用数组。你需要给它一个字符串。
$response = 'Your email and / or password were incorrect.';
throw new \Exception($response);
阅读错误:
例外([字符串 $例外[,长 $ code [,例外) $ previous = NULL]]])
答案 1 :(得分:1)
如果要以数组作为参数抛出异常,可以json_encode数组,使其成为字符串。
$response = array('login_email' => 'sometext', 'last_query' => 'sometext');
throw new \Exception(json_encode($response));
还要看一下json_encode的第二个参数:你可以添加JSON_PRETTY_PRINT来缩进错误(它更易读,但需要更多空间),或者你可以使用像JSON Viewer这样的工具来格式化Notepad ++看着你的json字符串。
答案 2 :(得分:0)
如果要抛出包含数组的异常,则可以创建自己的异常类并对其进行扩展 - Can you throw an array instead of a string as an exception in php?