7

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?

0

3 Answers 3

15

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]]])

Sign up to request clarification or add additional context in comments.

5 Comments

That's what I thought, although I'm pretty sure in the past I've managed to pass the array as argument - thanks anyway.
If you're wanting to specify the type of Exception, you could pass it a code. new Exception($response,2);
There are also several predefined exception types in SPL, if any of those are applicable.
But they all extend the main Exception - and inherit the arguments sent to the constructor - isn't that right?
As an additional tip, in case you're using a constant as second parameter, make sure it is actually defined...
2

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.

Comments

0

If you want to throw an exception which includes an array, then you can create your own exception class and extend it - Can you throw an array instead of a string as an exception in php?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.