Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 549
Spencer Mark Avatar asked Aug 31 '12 16:08

Spencer Mark


People also ask

What is throw exception PHP?

Throwing Exceptions in PHP Defined in the constructor, and accessed via the getMessage() method, the message is the human-readable error that can often be related to the end user.

How can I get error code from exception in PHP?

The getMessage() method returns a description of the error or behaviour that caused the exception to be thrown.

Which are valid PHP error handling keywords?

The following keywords are used for PHP exception handling. Try: The try block contains the code that may potentially throw an exception. All of the code within the try block is executed until an exception is potentially thrown. Throw: The throw keyword is used to signal the occurrence of a PHP exception.


2 Answers

Exception() won't take an array. 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]]])

like image 79
Wayne Whitty Avatar answered Sep 25 '22 22:09

Wayne Whitty


If you want to throw an exception with an array as parameter, you can json_encode your array so it becomes a string.

$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.

like image 37
T30 Avatar answered Sep 26 '22 22:09

T30