简体   繁体   English

PHP:错误:抛出数组异常的异常参数错误

[英]PHP : Error: Wrong parameters for Exception with thrown Array Exception

I'm throwing the exception using the array like so: 我正在使用这样的数组抛出异常:

$response = array('login_email' => '<div class="warning">Your email and / or password were incorrect</div>');

throw new \Exception($response);

and what I'm catching is: 而我所追捕的是:

Error: Wrong parameters for Exception([string $exception [, long $code [, Exception $previous = NULL]]])

Any idea? 任何的想法?

Exception() won't take an array. Exception()不会采用数组。 You need to give it a string. 你需要给它一个字符串。

$response = 'Your email and / or password were incorrect.';

throw new \Exception($response);

Read the error: 阅读错误:

Exception([ string $exception [, long $code [, Exception $previous = NULL]]]) 异常([ string $ exception [, long $ code [, Exception $ previous = NULL]]])

If you want to throw an exception with an array as parameter, you can json_encode your array so it becomes a string. 如果要将数组作为参数抛出异常,则可以对数组进行json_encode以使其成为字符串。

$response = array('login_email' => 'sometext', 'last_query' => 'sometext');
throw new \Exception(json_encode($response));

Have a look also at the second parameter of json_encode: you can add JSON_PRETTY_PRINT to have you error indented (it's more readable but it takes more space), or you can use a tool like JSON Viewer for Notepad++ to format your json string when looking at it. 另请参阅json_encode的第二个参数:您可以添加JSON_PRETTY_PRINT以使错误缩进(它更易读,但需要更多空间),或者您可以使用JSON Viewer for Notepad ++等工具在查看时格式化json字符串它。

如果你想抛出一个包含数组的异常,那么你可以创建自己的异常类并扩展它 - 你可以在php中抛出一个数组而不是字符串作为异常吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM