tags:

views:

70

answers:

5

I am trying to get some errors returned in JSON format. So, I made a class level var:

public $errors = Array();

So, lower down in the script, different functions might return an error, and add their error to the $errors array. But, I have to use return; in some places to stop the script after an error occurs.

So, when I do that, how can I still run my last error function that will return all the gathered errors? How can I get around the issue of having to stop the script, but still wanting to return the errors for why I needed to stop the script?!

+1  A: 

Really bare bones skeleton:

$errors = array();

function add_error($message, $die = false) {
  global $errors;
  $errors[] = $message;
  if ($die) {
    die(implode("\n", $errors));
  }
}
cletus
A: 

You can register a shutdown function.

ceejayoz
Didn ' t assume this that the script is 'completed'?
daemonfire300
Yes, you would need to call `exit()` when an error condition is a fatal one.
ceejayoz
A: 
  1. Add the errors to the current $_SESSION
  2. Add the latest errors to any kind of cache, XML or some storage

If the code 'stops':

// code occurs error

die(print_r($errors));

daemonfire300
A: 

If you are using PHP5+ your class can have a destructor method:

public function __destruct() {
    die(var_dump($this->errors));
}
cballou
A: 

You can use a trick involving do{}.

do {
    if(something) {
        // add error
    }
    if(something_else) {
        // add error
        break;
    }
    if(something) {
        // add error
    }
}while(0);

// check/print errors

Notice break, you can use it to break out of the do scope at any time, after which you have the final error returning logic. Or you could just what's inside do{} inside a function, and use return instead of break, which would be even better. Or yes, even better, a class with a destructor.

treznik