views:

69

answers:

2

I have an application based on Zend Framwork. In one Model I am calling a method from another Model. When I call this method I use try-cath block for handling of strange situations. Model1.

try {
   $result  =  Module_Model2_Name->method();
} catch (Exception $e) {
   // Do Something
}

Catch should be work if we find a throw in try block. But I don't know about behaviour of my application. If it is a some application error in Model2 method it should be throw an Exception. In method of Model2 I do the next thing, but it doesn't work:

set_error_handler(create_function('$m = "Error"','throw new Exception($m);'), E_ALL);

How can I throw an Exception on every PHP application error? Thank you very much. Sorry for my English.

+6  A: 

It looks good to me (tested it).

<?php
set_error_handler(create_function('$nr, $msg = "Error"','throw new Exception($m);'), E_ALL);
try{
    foreach($notHere as $var){}
}
catch(Exception $e){
    var_dump($e);
}
?>

Please note that:

The following error types cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the file where set_error_handler() is called.

Taken from the PHP manual.

Alin Purcaru
-1. It isn't an answer. I know this part of manual. It isn't help me.
Alexander.Plutov
Please explain then what do you want to do? This example works good. PHP throws an exception every time PHP error occures.
donis
Beg your pardon? What else would you need? You asked: *How can I throw an Exception on every PHP application error?* and I gave you a code snippet that does that. I also pointed out that some errors can't be caught with an error handler by giving you a quote from the manual.
Alin Purcaru
+1 For answering the question.
Tim Lytle
Sorry. Yes. it works.
Alexander.Plutov
Yes, it is correct. It worked in my application.
lakum4stackof
@AlinPurcaru: You missed error number param. Should be: `set_error_handler(create_function('$nr, $msg = "Default error message"','throw new Exception("$msg);'), E_ALL);`
takeshin
@Alin Purcaru: One more typo to fix ;)
takeshin
+1  A: 

My version:

function custom_error_handler($errno, $errstr, $errfile, $errline, $errcontext)
{
    $constants = get_defined_constants(1);

    $eName = 'Unknown error type';
    foreach ($constants['Core'] as $key => $value) {
        if (substr($key, 0, 2) == 'E_' && $errno == $value) {
            $eName = $key;
            break;
        }
    }

    $msg = $eName . ': ' . $errstr . ' in ' . $errfile . ', line ' . $errline;

    throw new Exception($msg);
}

set_error_handler('custom_error_handler', E_ALL);
takeshin
Thanks. It works pretty.
Alexander.Plutov