Throw an exception on every application error

I have an application based on Zend Framwork. In one model, I call a method from another model. When I call this method, I use the try-cath block to handle strange situations. Model1.

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

Catch should work if we find a throw in the try block. But I do not know about the behavior of my application. If this is some application error in the Model2 method, this should be an Exception. In the Model2 method, I do the following, but this does not work:

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

How can I throw an exception on every error of a PHP application? Many thanks. Sorry for my English.

+3
source share
2 answers

I feel good (verified).

<?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);
}
?>

:

: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING E_STRICT , set_error_handler().

PHP.

+8

:

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);
+4

Source: https://habr.com/ru/post/1769535/


All Articles