Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to throw an array exception in php

So I have an error message that gets thrown in one file

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

and in another file I have

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

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

like image 316
CodeCrack Avatar asked Jan 11 '12 18:01

CodeCrack


1 Answers

The problem is that You're trying to merge array with a string. It'll always end like this.

Maybe You should pass to exception an array, so You can later make use of 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) {
    // ...
}
?>
like image 100
radmen Avatar answered Sep 20 '22 11:09

radmen