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?

Spencer Mark
  • 5,263
  • 9
  • 29
  • 58

3 Answers3

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

Wayne Whitty
  • 19,513
  • 7
  • 44
  • 66
  • That's what I thought, although I'm pretty sure in the past I've managed to pass the array as argument - thanks anyway. – Spencer Mark Aug 31 '12 at 16:17
  • If you're wanting to specify the type of Exception, you could pass it a code. new Exception($response,2); – Wayne Whitty Aug 31 '12 at 16:20
  • There are also several predefined exception types in [SPL](http://us2.php.net/manual/en/spl.exceptions.php), if any of those are applicable. – Wiseguy Aug 31 '12 at 16:23
  • But they all extend the main Exception - and inherit the arguments sent to the constructor - isn't that right? – Spencer Mark Aug 31 '12 at 16:25
  • As an additional tip, in case you're using a constant as second parameter, make sure it is actually defined... – Cédric Françoys Oct 30 '18 at 09:27
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.

T30
  • 11,422
  • 7
  • 53
  • 57
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?

Community
  • 1
  • 1
Westy
  • 11
  • 1