Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwing an Exception on every application error

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.

like image 491
Alex Pliutau Avatar asked Dec 16 '22 20:12

Alex Pliutau


2 Answers

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.

like image 78
Alin Purcaru Avatar answered Dec 31 '22 12:12

Alin Purcaru


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);
like image 43
takeshin Avatar answered Dec 31 '22 12:12

takeshin