How to remove array exception in php

So, I have an error message that is thrown into a single file

$error_message = "Error received for " . $service . ": " . $_r['status'] . "\n" . "Message received: " . $_r['errors']; throw new My_Exception($error_message); 

and in another file

 try { //blah blah } catch( My_Exception $e ) { var_export($e->getMessage()); } 

The problem, however, is that $ _r ['errors'] is ARRAY and gets $ e-> getMessage (), just prints it as an "Array". How can I change this code to access an array?

+7
source share
3 answers

To convert a complex data structure, such as an array, to a string (for example, for error messages), you can use print_r & shy; Docs and set the second parameter to TRUE :

 ... ": " . print_r($_r['status'], TRUE) . "\n" ... 
+8
source

The problem is that you are trying to combine an array with a string. It will always be so.

Maybe you should go to the exception of the array in order to subsequently use it?

 <?php class myException extends Exception { private $params; public function setParams(array $params) { $this->params = $params; } public function getParams() { return $this->params; } } // later it can be used like this: try { $exception = new myException('Error!'); $exception->setParams(array('status' => 1, 'errors' => array()); throw $exception; } catch (myException $e) { // ... } ?> 
+14
source

so your sample code will not be good, but assuming

 $_r['errors'] = array( 'Message 1', 'Message 2', 'Message 3', 'Message 4', 'Message 5', ); 

Then

 $error_message = "Error received for " . $service . ": \n" . impolode("\n", $_r['errors']) . "\n" . "Message received: " . $_r['errors']; throw new My_Exception($error_message); 

The key takes your array of error messages and combines them with newlines (or something else)

But I agree with the comment that you may incorrectly use the Exception structure. Can you post what you are trying to do?

The general rule is that you throw an exception for each unique event. You do not collect a bunch of error messages, and then throw them all at once.

0
source

All Articles