Fatal error php перехват

I can use set_error_handler() to catch most PHP errors, but it doesn't work for fatal (E_ERROR) errors, such as calling a function that doesn't exist. Is there another way to catch these errors? I...

Nice solution found in Zend Framework 2:

/**
 * ErrorHandler that can be used to catch internal PHP errors
 * and convert to an ErrorException instance.
 */
abstract class ErrorHandler
{
    /**
     * Active stack
     *
     * @var array
     */
    protected static $stack = array();

    /**
     * Check if this error handler is active
     *
     * @return bool
     */
    public static function started()
    {
        return (bool) static::getNestedLevel();
    }

    /**
     * Get the current nested level
     *
     * @return int
     */
    public static function getNestedLevel()
    {
        return count(static::$stack);
    }

    /**
     * Starting the error handler
     *
     * @param int $errorLevel
     */
    public static function start($errorLevel = E_WARNING)
    {
        if (!static::$stack) {
            set_error_handler(array(get_called_class(), 'addError'), $errorLevel);
        }

        static::$stack[] = null;
    }

    /**
     * Stopping the error handler
     *
     * @param  bool $throw Throw the ErrorException if any
     * @return null|ErrorException
     * @throws ErrorException If an error has been catched and $throw is true
     */
    public static function stop($throw = false)
    {
        $errorException = null;

        if (static::$stack) {
            $errorException = array_pop(static::$stack);

            if (!static::$stack) {
                restore_error_handler();
            }

            if ($errorException && $throw) {
                throw $errorException;
            }
        }

        return $errorException;
    }

    /**
     * Stop all active handler
     *
     * @return void
     */
    public static function clean()
    {
        if (static::$stack) {
            restore_error_handler();
        }

        static::$stack = array();
    }

    /**
     * Add an error to the stack
     *
     * @param int    $errno
     * @param string $errstr
     * @param string $errfile
     * @param int    $errline
     * @return void
     */
    public static function addError($errno, $errstr = '', $errfile = '', $errline = 0)
    {
        $stack = & static::$stack[count(static::$stack) - 1];
        $stack = new ErrorException($errstr, 0, $errno, $errfile, $errline, $stack);
    }
}

This class allows you to start the specific ErrorHandler sometimes if you need it. And then you can also stop the Handler.

Use this class e.g. like this:

ErrorHandler::start(E_WARNING);
$return = call_function_raises_E_WARNING();

if ($innerException = ErrorHandler::stop()) {
    throw new Exception('Special Exception Text', 0, $innerException);
}

// or
ErrorHandler::stop(true); // directly throws an Exception;

Link to the full class code:
https://github.com/zendframework/zf2/blob/master/library/Zend/Stdlib/ErrorHandler.php

A maybe better solution is that one from Monolog:

Link to the full class code:
https://github.com/Seldaek/monolog/blob/master/src/Monolog/ErrorHandler.php

It can also handle FATAL_ERRORS using the register_shutdown_function function. According to this class a FATAL_ERROR is one of the following array(E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR).

class ErrorHandler
{
    // [...]

    public function registerExceptionHandler($level = null, $callPrevious = true)
    {
        $prev = set_exception_handler(array($this, 'handleException'));
        $this->uncaughtExceptionLevel = $level;
        if ($callPrevious && $prev) {
            $this->previousExceptionHandler = $prev;
        }
    }

    public function registerErrorHandler(array $levelMap = array(), $callPrevious = true, $errorTypes = -1)
    {
        $prev = set_error_handler(array($this, 'handleError'), $errorTypes);
        $this->errorLevelMap = array_replace($this->defaultErrorLevelMap(), $levelMap);
        if ($callPrevious) {
            $this->previousErrorHandler = $prev ?: true;
        }
    }

    public function registerFatalHandler($level = null, $reservedMemorySize = 20)
    {
        register_shutdown_function(array($this, 'handleFatalError'));

        $this->reservedMemory = str_repeat(' ', 1024 * $reservedMemorySize);
        $this->fatalLevel = $level;
    }

    // [...]
}

Table of Contents

  • Extending Exceptions

PHP has an exception model similar to that of other programming
languages. An exception can be thrown, and caught («catched») within
PHP. Code may be surrounded in a try block, to facilitate the catching
of potential exceptions. Each try must have at least one corresponding
catch or finally block.

If an exception is thrown and its current function scope has no catch
block, the exception will «bubble up» the call stack to the calling
function until it finds a matching catch block. All finally blocks it encounters
along the way will be executed. If the call stack is unwound all the way to the
global scope without encountering a matching catch block, the program will
terminate with a fatal error unless a global exception handler has been set.

The thrown object must be an instanceof Throwable.
Trying to throw an object that is not will result in a PHP Fatal Error.

As of PHP 8.0.0, the throw keyword is an expression and may be used in any expression
context. In prior versions it was a statement and was required to be on its own line.

catch

A catch block defines how to respond to a thrown exception. A catch
block defines one or more types of exception or error it can handle, and
optionally a variable to which to assign the exception. (The variable was
required prior to PHP 8.0.0.) The first catch block a thrown exception
or error encounters that matches the type of the thrown object will handle
the object.

Multiple catch blocks can be used to catch different classes of
exceptions. Normal execution (when no exception is thrown within the try
block) will continue after that last catch block defined in sequence.
Exceptions can be thrown (or re-thrown) within a catch block. If not,
execution will continue after the catch block that was triggered.

When an exception is thrown, code following the statement will not be
executed, and PHP will attempt to find the first matching catch block.
If an exception is not caught, a PHP Fatal Error will be issued with an
«Uncaught Exception ...» message, unless a handler has
been defined with set_exception_handler().

As of PHP 7.1.0, a catch block may specify multiple exceptions
using the pipe (|) character. This is useful for when
different exceptions from different class hierarchies are handled the
same.

As of PHP 8.0.0, the variable name for a caught exception is optional.
If not specified, the catch block will still execute but will not
have access to the thrown object.

finally

A finally block may also be specified after or
instead of catch blocks. Code within the finally block will always be
executed after the try and catch blocks, regardless of whether an
exception has been thrown, and before normal execution resumes.

One notable interaction is between the finally block and a return statement.
If a return statement is encountered inside either the try or the catch blocks,
the finally block will still be executed. Moreover, the return statement is
evaluated when encountered, but the result will be returned after the finally block
is executed. Additionally, if the finally block also contains a return statement,
the value from the finally block is returned.

Global exception handler

If an exception is allowed to bubble up to the global scope, it may be caught
by a global exception handler if set. The set_exception_handler()
function can set a function that will be called in place of a catch block if no
other block is invoked. The effect is essentially the same as if the entire program
were wrapped in a trycatch block with that function as the catch.

Notes

Note:

Internal PHP functions mainly use
Error reporting, only modern
Object-oriented
extensions use exceptions. However, errors can be easily translated to
exceptions with ErrorException.
This technique only works with non-fatal errors, however.

Example #1 Converting error reporting to exceptions


<?php
function exceptions_error_handler($severity, $message, $filename, $lineno) {
throw new
ErrorException($message, 0, $severity, $filename, $lineno);
}
set_error_handler('exceptions_error_handler');
?>

Examples

Example #2 Throwing an Exception


<?php
function inverse($x) {
if (!
$x) {
throw new
Exception('Division by zero.');
}
return
1/$x;
}

try {
echo

inverse(5) . "n";
echo
inverse(0) . "n";
} catch (
Exception $e) {
echo
'Caught exception: ', $e->getMessage(), "n";
}
// Continue execution
echo "Hello Worldn";
?>

The above example will output:

0.2
Caught exception: Division by zero.
Hello World

Example #3 Exception handling with a finally block


<?php
function inverse($x) {
if (!
$x) {
throw new
Exception('Division by zero.');
}
return
1/$x;
}

try {
echo

inverse(5) . "n";
} catch (
Exception $e) {
echo
'Caught exception: ', $e->getMessage(), "n";
} finally {
echo
"First finally.n";
}

try {
echo

inverse(0) . "n";
} catch (
Exception $e) {
echo
'Caught exception: ', $e->getMessage(), "n";
} finally {
echo
"Second finally.n";
}
// Continue execution
echo "Hello Worldn";
?>

The above example will output:

0.2
First finally.
Caught exception: Division by zero.
Second finally.
Hello World

Example #4 Interaction between the finally block and return


<?phpfunction test() {
try {
throw new
Exception('foo');
} catch (
Exception $e) {
return
'catch';
} finally {
return
'finally';
}
}

echo

test();
?>

The above example will output:

Example #5 Nested Exception


<?phpclass MyException extends Exception { }

class

Test {
public function
testing() {
try {
try {
throw new
MyException('foo!');
} catch (
MyException $e) {
// rethrow it
throw $e;
}
} catch (
Exception $e) {
var_dump($e->getMessage());
}
}
}
$foo = new Test;
$foo->testing();?>

The above example will output:

Example #6 Multi catch exception handling


<?phpclass MyException extends Exception { }

class

MyOtherException extends Exception { }

class

Test {
public function
testing() {
try {
throw new
MyException();
} catch (
MyException | MyOtherException $e) {
var_dump(get_class($e));
}
}
}
$foo = new Test;
$foo->testing();?>

The above example will output:

Example #7 Omitting the caught variable

Only permitted in PHP 8.0.0 and later.


<?phpclass SpecificException extends Exception {}

function

test() {
throw new
SpecificException('Oopsie');
}

try {

test();
} catch (
SpecificException) {
print
"A SpecificException was thrown, but we don't care about the details.";
}
?>

Example #8 Throw as an expression

Only permitted in PHP 8.0.0 and later.


<?phpclass SpecificException extends Exception {}

function

test() {
do_something_risky() or throw new Exception('It did not work');
}

try {

test();
} catch (
Exception $e) {
print
$e->getMessage();
}
?>

ask at nilpo dot com

13 years ago


If you intend on creating a lot of custom exceptions, you may find this code useful.  I've created an interface and an abstract exception class that ensures that all parts of the built-in Exception class are preserved in child classes.  It also properly pushes all information back to the parent constructor ensuring that nothing is lost.  This allows you to quickly create new exceptions on the fly.  It also overrides the default __toString method with a more thorough one.

<?php
interface IException
{
   
/* Protected methods inherited from Exception class */
   
public function getMessage();                 // Exception message
   
public function getCode();                    // User-defined Exception code
   
public function getFile();                    // Source filename
   
public function getLine();                    // Source line
   
public function getTrace();                   // An array of the backtrace()
   
public function getTraceAsString();           // Formated string of trace

        /* Overrideable methods inherited from Exception class */

public function __toString();                 // formated string for display
   
public function __construct($message = null, $code = 0);
}

abstract class

CustomException extends Exception implements IException
{
    protected
$message = 'Unknown exception';     // Exception message
   
private   $string;                            // Unknown
   
protected $code    = 0;                       // User-defined exception code
   
protected $file;                              // Source filename of exception
   
protected $line;                              // Source line of exception
   
private   $trace;                             // Unknownpublic function __construct($message = null, $code = 0)
    {
        if (!
$message) {
            throw new
$this('Unknown '. get_class($this));
        }
       
parent::__construct($message, $code);
    }

        public function

__toString()
    {
        return
get_class($this) . " '{$this->message}' in {$this->file}({$this->line})n"
                               
. "{$this->getTraceAsString()}";
    }
}
?>

Now you can create new exceptions in one line:

<?php
class TestException extends CustomException {}
?>

Here's a test that shows that all information is properly preserved throughout the backtrace.

<?php
function exceptionTest()
{
    try {
        throw new
TestException();
    }
    catch (
TestException $e) {
        echo
"Caught TestException ('{$e->getMessage()}')n{$e}n";
    }
    catch (
Exception $e) {
        echo
"Caught Exception ('{$e->getMessage()}')n{$e}n";
    }
}

echo

'<pre>' . exceptionTest() . '</pre>';
?>

Here's a sample output:

Caught TestException ('Unknown TestException')
TestException 'Unknown TestException' in C:xampphtdocsCustomExceptionCustomException.php(31)
#0 C:xampphtdocsCustomExceptionExceptionTest.php(19): CustomException->__construct()
#1 C:xampphtdocsCustomExceptionExceptionTest.php(43): exceptionTest()
#2 {main}


Johan

11 years ago


Custom error handling on entire pages can avoid half rendered pages for the users:

<?php
ob_start
();
try {
   
/*contains all page logic
    and throws error if needed*/
   
...
} catch (
Exception $e) {
 
ob_end_clean();
 
displayErrorPage($e->getMessage());
}
?>


christof+php[AT]insypro.com

5 years ago


In case your E_WARNING type of errors aren't catchable with try/catch you can change them to another type of error like this:

<?php
    set_error_handler
(function($errno, $errstr, $errfile, $errline){
            if(
$errno === E_WARNING){
               
// make it more serious than a warning so it can be caught
               
trigger_error($errstr, E_ERROR);
                return
true;
            } else {
               
// fallback to default php error handler
               
return false;
            }
    });

    try {

// code that might result in a E_WARNING
   
} catch(Exception $e){
           
// code to handle the E_WARNING (it's actually changed to E_ERROR at this point)
   
} finally {
           
restore_error_handler();
    }
?>


Shot (Piotr Szotkowski)

14 years ago


‘Normal execution (when no exception is thrown within the try block, *or when a catch matching the thrown exception’s class is not present*) will continue after that last catch block defined in sequence.’

‘If an exception is not caught, a PHP Fatal Error will be issued with an “Uncaught Exception …” message, unless a handler has been defined with set_exception_handler().’

These two sentences seem a bit contradicting about what happens ‘when a catch matching the thrown exception’s class is not present’ (and the second sentence is actually correct).


Simo

7 years ago


#3 is not a good example. inverse("0a") would not be caught since (bool) "0a" returns true, yet 1/"0a" casts the string to integer zero and attempts to perform the calculation.

Edu

9 years ago


The "finally" block can change the exception that has been throw by the catch block.

<?php
try{
        try {
                throw new
Exception("Hello");
        } catch(
Exception $e) {
                echo
$e->getMessage()." catch inn";
                throw
$e;
        } finally {
                echo
$e->getMessage()." finally n";
                throw new
Exception("Bye");
        }
} catch (
Exception $e) {
        echo
$e->getMessage()." catch outn";
}
?>

The output is:

Hello catch in
Hello finally
Bye catch out


daviddlowe dot flimm at gmail dot com

5 years ago


Starting in PHP 7, the classes Exception and Error both implement the Throwable interface. This means, if you want to catch both Error instances and Exception instances, you should catch Throwable objects, like this:

<?phptry {
    throw new
Error( "foobar" );
   
// or:
    // throw new Exception( "foobar" );
}
catch (
Throwable $e) {
   
var_export( $e );
}
?>


mlaopane at gmail dot com

4 years ago


<?php/**
* You can catch exceptions thrown in a deep level function
*/
function employee()
{
    throw new
Exception("I am just an employee !");
}

function

manager()
{
   
employee();
}

function

boss()
{
    try {
       
manager();
    } catch (
Exception $e) {
        echo
$e->getMessage();
    }
}
boss(); // output: "I am just an employee !"

telefoontoestel at nospam dot org

8 years ago


When using finally keep in mind that when a exit/die statement is used in the catch block it will NOT go through the finally block.

<?php
try {
    echo
"try block<br />";
    throw new
Exception("test");
} catch (
Exception $ex) {
    echo
"catch block<br />";
} finally {
    echo
"finally block<br />";
}
// try block
// catch block
// finally block
?>

<?php
try {
    echo
"try block<br />";
    throw new
Exception("test");
} catch (
Exception $ex) {
    echo
"catch block<br />";
    exit(
1);
} finally {
    echo
"finally block<br />";
}
// try block
// catch block
?>


Tom Polomsk

8 years ago


Contrary to the documentation it is possible in PHP 5.5 and higher use only try-finally blocks without any catch block.

Sawsan

11 years ago


the following is an example of a re-thrown exception and the using of getPrevious function:

<?php

$name

= "Name";//check if the name contains only letters, and does not contain the word nametry
   {
   try
     {
      if (
preg_match('/[^a-z]/i', $name))
       {
           throw new
Exception("$name contains character other than a-z A-Z");
       }  
       if(
strpos(strtolower($name), 'name') !== FALSE)
       {
          throw new
Exception("$name contains the word name");
       }
       echo
"The Name is valid";
     }
   catch(
Exception $e)
     {
     throw new
Exception("insert name again",0,$e);
     }
   }

catch (

Exception $e)
   {
   if (
$e->getPrevious())
   {
    echo
"The Previous Exception is: ".$e->getPrevious()->getMessage()."<br/>";
   }
   echo
"The Exception is: ".$e->getMessage()."<br/>";
   }
?>


lscorionjs at gmail dot com

24 days ago


<?phptry {
 
$str = 'hi';
  throw new
Exception();
} catch (
Exception) {
 
var_dump($str);
} finally {
 
var_dump($str);
}
?>

Output:
string(2) "hi"
string(2) "hi"

ilia-yats at ukr dot net

1 month ago


Note some undocumented details about exceptions thrown from 'finally' blocks.

When exception is thrown from 'finally' block, it overrides the original not-caught (or re-thrown) exception. So the behavior is similar to 'return': value returned from 'finally' overrides the one returned earlier. And the original exception is automatically appended to the exceptions chain, i.e. becomes 'previous' for the new one. Example:
<?php
try {
    try {
        throw new
Exception('thrown from try');
    } finally {
        throw new
Exception('thrown from finally');
    }
} catch(
Exception $e) {
    echo
$e->getMessage();
    echo
PHP_EOL;
    echo
$e->getPrevious()->getMessage();
}
// will output:
// thrown from finally
// thrown from try
?>

Example with re-throwing:
<?php
try {
    try {
        throw new
Exception('thrown from try');
    } catch (
Exception $e) {
        throw new
Exception('thrown from catch');
    } finally {
        throw new
Exception('thrown from finally');
    }
} catch(
Exception $e) {
    echo
$e->getMessage();
    echo
PHP_EOL;
    echo
$e->getPrevious()->getMessage();
}
// will output:
// thrown from finally
// thrown from catch
?>

The same happens even if explicitly pass null as previous exception:
<?php
try {
    try {
        throw new
Exception('thrown from try');
    } finally {
        throw new
Exception('thrown from finally', null, null);
    }
} catch(
Exception $e) {
    echo
$e->getMessage();
    echo
PHP_EOL;
    echo
$e->getPrevious()->getMessage();
}
// will output:
// thrown from finally
// thrown from try
?>

Also it is possible to pass previous exception explicitly, the 'original' one will be still appended to the chain, e.g.:
<?php
try {
    try {
        throw new
Exception('thrown from try');
    } finally {
        throw new
Exception(
           
'thrown from finally',
           
null,
            new
Exception('Explicitly set previous!')
        );
    }
} catch(
Exception $e) {
    echo
$e->getMessage();
    echo
PHP_EOL;
    echo
$e->getPrevious()->getMessage();
    echo
PHP_EOL;
    echo
$e->getPrevious()->getPrevious()->getMessage();
}
// will output:
// thrown from finally
// Explicitly set previous!
// thrown from try
?>

This seems to be true for versions 5.6-8.2.


Daan

1 year ago


I would like to emphasise that you can not rethrow an Exception inside a catch-block and expect that the next catch-block will handle it.

<?php try {
    throw new
RuntimeException('error');           
} catch (
RuntimeException $e) {
    throw
$e;
} catch (
Exception $e) {
   
// this will not be executed[
}
?>


Пример демонстрирует обработку ошибок на этапе выполнения программы на PHP.
Особенность этого примера заключается в перехвате всего вывода на экран с помощью задания обработчика для
функции ob_start().
Таким образом можно перехватить вывод ошибок,
для которых стандартный обработчик вызван не будет.

// мы будем сами обрабатывать ВСЕ ошибки
error_reporting(E_ALL);

// определенная пользователем функция обработки ошибок
function userErrorHandler ($errno, $errmsg, $filename, $linenum, $vars) {
    // дата и время для записи об ошибке
    $dt = date("Y-m-d H:i:s (T)");

    // определение ассоциативного массива строк ошибок
    // на самом деле следует рассматривать только элементы 2,8,256,512 и 1024
    $errortype = array (
                1   =>  "Ошибка",
                2   =>  "Предупреждение",
                4   =>  "Ошибка синтаксического анализа",
                8   =>  "Замечание",
                16  =>  "Ошибка ядра",
                32  =>  "Предупреждение ядра",
                64  =>  "Ошибка компиляции",
                128 =>  "Предупреждение компиляции",
                256 =>  "Ошибка пользователя",
                512 =>  "Предупреждение пользователя",
                1024=>  "Замечание пользователя"
                );
    // набор ошибок, для которого будут сохраняться значения переменных
    $user_errors = array(E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE);

    $err  = $dt." ".$errortype[$errno]." № ".$errno."n";
    $err .= $errmsg."n";
    $err .= "Вызов из ".$filename." строка № ".$linenum."n";

    ob_end_clean();
    ob_start();
    print_r($vars);
    $v = "Переменные:".ob_get_contents()."n";
    ob_end_clean();
    ob_start("error_callback");

    // сохранить протокол ошибок и отправить его мылом
    mail('error@htmlweb.ru', 'PHP error report', $err.$v, "Content-Type: text/plain; charset=windows-1251" ) or die("Ошибка при отправке сообщения об ошибке");
    error_log($err."n", 3, dirname(__FILE__) . "/log/error.log") or die("Ошибка записи сообщения об ошибке в файл");
}

function error_callback($buffer) {
    // если на экран будет выведено сообщение о фатальной ошибке, мы его сможем обработать
    if (preg_match("/<b>error</b>.*/",$buffer,$regs)) {
       $regs[0] = date("Y-m-d H:i:s (T)")."n".preg_replace("/<[/]?b(r /)?>/","",$regs[0])."n";
       mail('error@htmlweb.ru', 'PHP error report', $regs[0], "Content-Type: text/plain; charset=windows-1251" ) or die("Ошибка при отправке сообщения об ошибке");
       error_log($regs[0], 3, dirname(__FILE__) . "/log/error.log") or die("Ошибка записи сообщения об ошибке в файл");
       return "Ошибка, выполнение прервано";
    }
    else
       return $buffer;
}

// Перехват вывода на экран
ob_start("error_callback");

// Перехват обработки ошибок
$old_error_handler = set_error_handler("userErrorHandler");

Перехват fatal error в PHP

Следующий пример позволяет назначить функцию-обработчик завершения любого PHP скрипта.
Этот обработчик получит управление и при возникновении fatal error.

// Определяем новую функцию-обработчик fatal error.
function myShutdownHandler() {
  if (@is_array($e = @error_get_last())) {
    $code = isset($e['type']) ? $e['type'] : 0;
    $msg = isset($e['message']) ? $e['message'] : '';
    $file = isset($e['file']) ? $e['file'] : '';
    $line = isset($e['line']) ? $e['line'] : '';
    if($code>0)userErrorHandler($code,$msg,$file,$line,'');

  }
}
register_shutdown_function('myShutdownHandler');

// вызываем ошибку:
$x = null;
$x->method();

userErrorHandler — процедура обработки ошибкок, описанная выше.

Is there say way to universally tell php to redirect to a certain page on any fatal errors?

Say i have a site with many different files, and i want to hide problems (while still logging them) and send the user to the same error page, no matter what the error is or what page they are on.

Lets just pretend for sake of argument that i dont want to see the errors, and the pages are being continuously edited and updated by robots who cause errors every 23rd or 51st page edit.

Im looking for something that perhaps involves the php.ini file, or htaccess, something that i can do site wide.

asked Nov 22, 2009 at 11:20

mrpatg's user avatar

1

See set_error_handler:

set_error_handler — Sets a
user-defined error handler function

Rudimentary example:

<?php

function errorHandler($n, $m, $f, $l) {
    header('Location: http://example.com/error.php');
}

set_error_handler('errorHandler');
...
?>

answered Nov 22, 2009 at 11:27

karim79's user avatar

karim79karim79

338k67 gold badges411 silver badges406 bronze badges

0

You can change the default 500 error page in Apache with the ‘ErrorDocument’ directive:

ErrorDocument 500 /500.html

This redirects a 500 Internal Server error to 500.html. You can also use a PHP page there and mail the referring page.

To catch the errors you can log those to an error.log file. Use the following two directives in your php.ini file:

error_log = /var/log/httpd/error_php  
log_errors = On  

Don’t forget to restart Apache.

answered Nov 22, 2009 at 11:30

TheGrandWazoo's user avatar

TheGrandWazooTheGrandWazoo

2,8311 gold badge17 silver badges15 bronze badges

0

First, change your php.ini to suppress error messages and to enable logging:

 display_errors=Off
 log_errors=On
 error_log=whatever/path

Write an error handler (unlike set_error_handler, this one also catches fatals)

register_shutdown_function('errorHandler');
function errorHandler() {
   $err = error_get_last();
   if($err)
     include "error_page.php"; // your custom error page
}

Put this code in a file and tell php to include it on every requrest (see auto_prepend_file @ http://php.net/manual/en/ini.core.php)

answered Nov 22, 2009 at 12:43

user187291's user avatar

user187291user187291

53k19 gold badges94 silver badges127 bronze badges

2

Is there say way to universally tell php to redirect to a certain page on any fatal errors?

Say i have a site with many different files, and i want to hide problems (while still logging them) and send the user to the same error page, no matter what the error is or what page they are on.

Lets just pretend for sake of argument that i dont want to see the errors, and the pages are being continuously edited and updated by robots who cause errors every 23rd or 51st page edit.

Im looking for something that perhaps involves the php.ini file, or htaccess, something that i can do site wide.

asked Nov 22, 2009 at 11:20

mrpatg's user avatar

1

See set_error_handler:

set_error_handler — Sets a
user-defined error handler function

Rudimentary example:

<?php

function errorHandler($n, $m, $f, $l) {
    header('Location: http://example.com/error.php');
}

set_error_handler('errorHandler');
...
?>

answered Nov 22, 2009 at 11:27

karim79's user avatar

karim79karim79

338k67 gold badges411 silver badges406 bronze badges

0

You can change the default 500 error page in Apache with the ‘ErrorDocument’ directive:

ErrorDocument 500 /500.html

This redirects a 500 Internal Server error to 500.html. You can also use a PHP page there and mail the referring page.

To catch the errors you can log those to an error.log file. Use the following two directives in your php.ini file:

error_log = /var/log/httpd/error_php  
log_errors = On  

Don’t forget to restart Apache.

answered Nov 22, 2009 at 11:30

TheGrandWazoo's user avatar

TheGrandWazooTheGrandWazoo

2,8311 gold badge17 silver badges15 bronze badges

0

First, change your php.ini to suppress error messages and to enable logging:

 display_errors=Off
 log_errors=On
 error_log=whatever/path

Write an error handler (unlike set_error_handler, this one also catches fatals)

register_shutdown_function('errorHandler');
function errorHandler() {
   $err = error_get_last();
   if($err)
     include "error_page.php"; // your custom error page
}

Put this code in a file and tell php to include it on every requrest (see auto_prepend_file @ http://php.net/manual/en/ini.core.php)

answered Nov 22, 2009 at 12:43

user187291's user avatar

user187291user187291

53k19 gold badges94 silver badges127 bronze badges

2

Хотя PHP уже давно поддерживает обработку исключений, однако, по сравнению с Java эта поддержка была довольно слабой

Первоначальная поддержка обработки исключений была введена в язык с 5 версии PHP, с двумя простыми встроенными классами исключений — Exception и ErrorException, с поддержкой дополнительных классов через SPL. Идея этого поста состоит в том, чтобы представить читателям современные возможности обработки исключений PHP. 

Новый интерфейс

Хотя PHP 7 предоставляет классы Error и Exception, давайте сначала затронем интерфейс Throwable . И Error и Exception классы реализуют Throwable интерфейс — это основа для любого объекта , который может быть брошен с помощью оператора throw. Единственное, что он не может быть реализован непосредственно в классах пользовательского пространства, только через расширение класса Exception. Кроме того, он обеспечивает единую точку для отлова обоих типов ошибок в одном выражении:

<?php

try {
// ваш код
} catch (Throwable $e) {
echo 'Очень хороший способ отловить исключения и ошибки';
}

Список доступных встроенных классов исключений начиная с PHP 7.4:

  • Exception
  • ErrorException
  • Error
  • ArgumentCountError
  • ArithmeticError
  • AssertionError
  • DivisionByZeroError
  • CompileError
  • ParseError
  • TypeError

Дополнительные классы исключений можно найти в стандартной библиотеке PHP . И наиболее заметным из расширений JSON является класс JsonException.

THROWABLE

Интерфейс Throwable  PHP 7:

interface Throwable
{
public function getMessage(): string; // Error reason
public function getCode(): int; // Error code
public function getFile(): string; // Error begin file
public function getLine(): int; // Error begin line
public function getTrace(): array; // Return stack trace as array like debug_backtrace()
public function getTraceAsString(): string; // Return stack trace as string
public function getPrevious(): Throwable; // Return previous `Trowable`
public function __toString(): string; // Convert into string
}

Вот иерархия Throwable:

interface Throwable
|- Error implements Throwable
|- ArithmeticError extends Error
|- DivisionByZeroError extends ArithmeticError
|- AssertionError extends Error
|- ParseError extends Error
|- TypeError extends Error
|- ArgumentCountError extends TypeError
|- Exception implements Throwable
|- ClosedGeneratorException extends Exception
|- DOMException extends Exception
|- ErrorException extends Exception
|- IntlException extends Exception
|- LogicException extends Exception
|- BadFunctionCallException extends LogicException
|- BadMethodCallException extends BadFunctionCallException
|- DomainException extends LogicException
|- InvalidArgumentException extends LogicException
|- LengthException extends LogicException
|- OutOfRangeException extends LogicException
|- PharException extends Exception
|- ReflectionException extends Exception
|- RuntimeException extends Exception
|- OutOfBoundsException extends RuntimeException
|- OverflowException extends RuntimeException
|- PDOException extends RuntimeException
|- RangeException extends RuntimeException
|- UnderflowException extends RuntimeException
|- UnexpectedValueException extends RuntimeException

Ошибка, почему?

В предыдущих версиях PHP ошибки обрабатывались совершенно иначе, чем исключения. Если возникала ошибка, то пока она не была фатальной, она могла быть обработана пользовательской функцией.

Проблема заключалась в том, что было несколько фатальных ошибок, которые не могли быть обработаны определяемым пользователем обработчиком ошибок. Это означало, что вы не могли корректно обрабатывать фатальные ошибки в PHP. Было несколько побочных эффектов, которые были проблематичными, такие как потеря контекста времени выполнения, деструкторы не вызывались, да и вообще иметь дело с ними было неудобно. В PHP 7 фатальные ошибки теперь являются исключениями, и мы можем легко их обработать. Фатальные ошибки приводят к возникновению исключений. Вам необходимо обрабатывать нефатальные ошибки с помощью функции обработки ошибок.

Вот пример ловли фатальной ошибки в PHP 7.1. Обратите внимание, что нефатальная ошибка не обнаружена.

<?php 

try {
// будет генерировать уведомление, которое не будет поймано
echo $someNotSetVariable;
// фатальная ошибка, которая сейчас на самом деле ловится
someNoneExistentFunction();
} catch (Error $e) {
echo "Error caught: " . $e->getMessage();
}

Этот скрипт выведет сообщение об ошибке при попытке доступа к недопустимой переменной. Попытка вызвать функцию, которая не существует, приведет к фатальной ошибке в более ранних версиях PHP, но в PHP 7.1 вы можете ее перехватить. Вот вывод для скрипта:

Notice: Undefined variable: someNotSetVariable on line 3
Error caught: Call to undefined function someNoneExistentFunction()

Константы ошибок

В PHP много констант, которые используются в отношении ошибок. Эти константы используются при настройке PHP для скрытия или отображения ошибок определенных классов.

Вот некоторые из наиболее часто встречающихся кодов ошибок:

  • E_DEPRECATED — интерпретатор сгенерирует этот тип предупреждений, если вы используете устаревшую языковую функцию. Сценарий обязательно продолжит работать без ошибок.
  • E_STRICT — аналогично E_DEPRECATED, — указывает на то, что вы используете языковую функцию, которая не является стандартной в настоящее время и может не работать в будущем. Сценарий будет продолжать работать без каких-либо ошибок.
  • E_PARSE — ваш синтаксис не может быть проанализирован, поэтому ваш скрипт не запустится. Выполнение скрипта даже не запустится.
  • E_NOTICE — движок просто выведет информационное сообщение. Выполнение скрипта не прервется, и ни одна из ошибок не будет выдана.
  • E_ERROR — скрипт не может продолжить работу, и завершится. Выдает ошибки, а как они будут обрабатываться, зависит от обработчика ошибок.
  • E_RECOVERABLE_ERROR — указывает на то, что, возможно, произошла опасная ошибка, и движок работает в нестабильном состоянии. Дальнейшее выполнение зависит от обработчика ошибок, и ошибка обязательно будет выдана.

Полный список констант можно найти в руководстве по PHP.

Функция обработчика ошибок

Функция set_error_handler() используется, чтобы сообщить PHP как обрабатывать стандартные ошибки, которые не являются экземплярами класса исключений Error. Вы не можете использовать функцию обработчика ошибок для фатальных ошибок. Исключения ошибок должны обрабатываться с помощью операторов try/catch. set_error_handler() принимает callback функцию в качестве своего параметра. Callback-функции в PHP могут быть заданы двумя способами: либо строкой, обозначающей имя функции, либо передачей массива, который содержит объект и имя метода (именно в этом порядке). Вы можете указать защищенные и приватные методы для callable в объекте. Вы также можете передать значение null, чтобы указать PHP вернуться к использованию стандартного механизма обработки ошибок. Если ваш обработчик ошибок не завершает программу и возвращает результат, ваш сценарий будет продолжать выполняться со строки, следующей за той, где произошла ошибка.

PHP передает параметры в вашу функцию обработчика ошибок. Вы можете опционально объявить их в сигнатуре функции, если хотите использовать их в своей функции.

Вот пример:

<?php

function myCustomErrorHandler(int $errNo, string $errMsg, string $file, int $line) {
echo "Ух ты, мой обработчик ошибок получил #[$errNo] в [$file] на [$line]: [$errMsg]";
}

set_error_handler('myCustomErrorHandler');

try {
why;
} catch (Throwable $e) {
echo 'И моя ошибка: ' . $e->getMessage();
}

Если вы запустите этот код в PHP-консоли php -a, вы должны получить похожий вывод:

Error #[2] occurred in [php shell code] at line [3]: [Use of undefined constant why - assumed 'why' (this will throw an Error in a future version of PHP)]

Самые известные PHP библиотеки , которые делают обширное использование РНР set_error_handler() и могут сделать хорошие представления исключений и ошибок являются whoops,  и Symony Debug, ErrorHandler компоненты. Я смело рекомендую использовать один из них. Если не собираетесь их использовать в своем проекте, то вы всегда можете черпать вдохновение из их кода. В то время как компонент Debug широко используется в экосистеме Symfony, Whoops остается библиотекой выбора для фреймворка Laravel . 

Для подробного и расширенного использования, пожалуйста, обратитесь к руководству по PHP для обработчика ошибок.

Отображение или подавление нефатальной ошибки

Когда ваше приложение выходит в продакшн, логично, что вы хотите скрыть все системные сообщения об ошибках во время работы, и ваш код должен работать без генерации предупреждений или сообщений. Если вы собираетесь показать сообщение об ошибке, убедитесь, что оно сгенерировано и не содержит информации, которая может помочь злоумышленнику проникнуть в вашу систему.

В вашей среде разработки вы хотите, чтобы все ошибки отображались, чтобы вы могли исправить все проблемы, с которыми они связаны, но в процессе работы вы хотите подавить любые системные сообщения, отправляемые пользователю.

Для этого вам нужно настроить PHP, используя следующие параметры в вашем файле php.ini:

  • display_errors – может быть установлен в false для подавления сообщений
  • log_errors – может использоваться для хранения сообщений об ошибках в файлах журнала
  • error_reporting – можно настроить, какие ошибки вызывают отчет

Лучше всего корректно обрабатывать ошибки в вашем приложении. В производственном процессе вы должны скорее регистрировать необработанные ошибки, чем разрешать их отображение пользователю. Функция error_log() может использоваться для отправки сообщения одной из определенных процедур обработки ошибок. Вы также можете использовать функцию error_log() для отправки электронных писем, но лично вы бы предпочли использовать хорошее решение для регистрации ошибок и получения уведомлений при возникновении ошибок, например Sentry или Rollbar .

Существует вещь, называемая оператором контроля ошибок ( @ ), который по своей сути может игнорировать и подавлять ошибки. Использование очень простое — просто добавьте любое выражение PHP с символом «собаки», и сгенерированная ошибка будет проигнорирована. Хотя использование этого оператора может показаться интересным, я призываю вас не делать этого. Мне нравится называть это живым пережитком прошлого.

Больше информации для всех функций, связанных с ошибками PHP, можно найти в руководстве.

Исключения (Exceptions)

Исключения являются основной частью объектно-ориентированного программирования и впервые были представлены в PHP 5.0. Исключением является состояние программы, которое требует специальной обработки, поскольку оно не выполняется ожидаемым образом. Вы можете использовать исключение, чтобы изменить поток вашей программы, например, чтобы прекратить что-либо делать, если некоторые предварительные условия не выполняются.

Исключение будет возникать в стеке вызовов, если вы его не перехватите. Давайте посмотрим на простой пример:

try {
print "это наш блок попыток n";
throw new Exception();
} catch (Exception $e) {
print "что-то пошло не так, есть улов!";
} finally {
print "эта часть всегда выполняется";
}

PHP включает в себя несколько стандартных типов исключений, а стандартная библиотека PHP (SPL) включает в себя еще несколько. Хотя вам не нужно использовать эти исключения, это означает, что вы можете использовать более детальное обнаружение ошибок и отчеты. Классы Exception и Error реализуют интерфейс Throwable и, как и любые другие классы, могут быть расширены. Это позволяет вам создавать гибкие иерархии ошибок и адаптировать обработку исключений. Только класс, который реализует класс Throwable, может использоваться с ключевым словом throw. Другими словами, вы не можете объявить свой собственный базовый класс и затем выбросить его как исключение.

Надежный код может встретить ошибку и справиться с ней. Разумная обработка исключений повышает безопасность вашего приложения и облегчает ведение журнала и отладку. Управление ошибками в вашем приложении также позволит вам предложить своим пользователям лучший опыт. В этом разделе мы рассмотрим, как отлавливать и обрабатывать ошибки, возникающие в вашем коде.

Ловля исключений

Вы должны использовать try/catch структуру:

<?php

class MyCustomException extends Exception { }

function throwMyCustomException() {
throw new MyCustomException('Здесь что-то не так.');
}

try {
throwMyCustomException();
} catch (MyCustomException $e) {
echo "Ваше пользовательское исключение поймано";
echo $e->getMessage();
} catch (Exception $e) {
echo "Стандартное исключение PHP";
}

Как видите, есть два предложения catch. Исключения будут сопоставляться с предложениями сверху вниз, пока тип исключения не будет соответствовать предложению catch. Эта очень простая функция throwMyCustomException() генерирует исключение MyCustomException, и мы ожидаем, что оно будет перехвачено в первом блоке. Любые другие исключения, которые произойдут, будут перехвачены вторым блоком. Здесь мы вызываем метод getMessage() из базового класса Exception. Вы можете найти больше информации о дополнительном методе в Exception PHP docs.

Кроме того, можно указать несколько исключений, разделяя их трубой ( | ).

Давайте посмотрим на другой пример:

<?php

class MyCustomException extends Exception { }
class MyAnotherCustomException extends Exception { }

try {
throw new MyAnotherCustomException;
} catch (MyCustomException | MyAnotherCustomException $e) {
echo "Caught : " . get_class($e);
}

Этот очень простой блок catch будет перехватывать исключения типа MyCustomException и MyAnotherCustomException.

Немного более продвинутый сценарий:

// exceptions.php
use SymfonyComponentHttpKernelExceptionNotFoundHttpException;

try {
throw new NotFoundHttpException();
} catch (Exception $e) {
echo 1;
} catch (NotFoundHttpException $e) {
echo 2;
} catch (Exception $e) {
echo 3;
} finally {
echo 4;
}

Это ваш окончательный ответ?

В PHP 5.5 и более поздних, блок finally также может быть указан после или вместо блоков catch. Код внутри блока finally всегда будет выполняться после блоков try и catch независимо от того, было ли выброшено исключение, и до возобновления нормального выполнения. Одним из распространенных применений блока finally является закрытие соединения с базой данных, но, наконец, его можно использовать везде, где вы хотите, чтобы код всегда выполнялся.

<?php

class MyCustomException extends Exception { }

function throwMyCustomException() {
throw new MyCustomException('Здесь что-то не так');
}

try {
throwMyCustomException();
} catch (MyCustomException $e) {
echo "Ваше пользовательское исключение поймано ";
echo $e->getMessage();
} catch (Exception $e) {
echo "Стандартное исключение PHP";
} finally {
echo "Я всегда тут";
}

Вот хороший пример того, как работают операторы PHP catch/finally:

<?php

try {
try {
echo 'a-';
throw new exception();
echo 'b-';
} catch (Exception $e) {
echo 'пойманный-';
throw $e;
} finally {
echo 'завершенный-';
}
} catch (Exception $e) {
echo 'конец-';
}

Функция обработчика исключений

Любое исключение, которое не было обнаружено, приводит к фатальной ошибке. Если вы хотите изящно реагировать на исключения, которые не перехватываются в блоках перехвата, вам нужно установить функцию в качестве обработчика исключений по умолчанию.

Для этого вы используете функцию set_exception_handler() , которая принимает вызываемый элемент в качестве параметра. Ваш сценарий завершится после того, как вызов будет выполнен.

Функция restore_exception_handler() вернет обработчик исключений к его предыдущему значению.

<?php

class MyCustomException extends Exception { }

function exception_handler($exception) {
echo "Uncaught exception: " , $exception->getMessage(), "n";
}

set_exception_handler('exception_handler');

try {
throw new Exception('Uncaught Exception');
} catch (MyCustomException $e) {
echo "Ваше пользовательское исключение поймано ";
echo $e->getMessage();
} finally {
echo "Я всегда тут";
}

print "Не выполнено";

Здесь простая функция exception_handler будет выполняться после блока finally, когда ни один из типов исключений не был сопоставлен. Последний вывод никогда не будет выполнен.

Для получения дополнительной информации обратитесь к документации PHP. 

Старый добрый «T_PAAMAYIM_NEKUDOTAYIM»

Вероятно, это было самое известное сообщение об ошибке PHP. В последние годы было много споров по этому поводу. Вы можете прочитать больше в отличном сообщении в блоге от Фила Осетра .  

Сегодня я с гордостью могу сказать, что если вы запустите этот код с PHP 7, то сообщение о T_PAAMAYIM_NEKUDOTAYIM больше не будет:

<?php

class foo
{
static $bar = 'baz';
}

var_dump('foo'::$bar);

// Output PHP < 7.0:
// PHP Parse error: syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM) in php shell code on line 1
// Output PHP > 7.0:
// string(3) "baz"
?>

В заключении

Со времени первого внедрения обработки исключений в PHP прошло много лет, пока мы не получили гораздо более надежную и зрелую обработку исключений, чем в Java. Обработка ошибок в PHP 7 получила много внимания, что делает его хорошим, открывая пространство для будущих улучшений, если мы действительно с сегодняшней точки зрения нуждаемся в них.

В PHP5 как и в других мощных языках программирования (например Java) существует механизм выброса и перехвата исключительных ситуаций.

Для этого необходимо поместить потенциально небезопасный код в блок try для перехвата исключения. Каждый try должен сопровождаться как минимум одним блоком catch.

Множественные блоки catch можно использовать для перехвата исключений различных классов. Меньше слов — больше дела:

class Generic
  {

      private $someVar;

      public function __construct($someVar)
      {
          $this->someVar = $someVar;
      }

      public function testValue($someOtherVar)
      {
          if($someOtherVar > 3) {
              throw new Exception('Значение параметра не может быть больше 3!');
          } else {
              echo $this->someVar + $someOtherVar;
          }
      }
  }

  $gen = new Generic(3);
  $gen->testValue(4);

Этот фрагмент кода превосходно демонстрирует процесс выброса исключения. Если вы сейчас запустите страницу с этим кодом, то получите сообщение на подобии этого:

Fatal error: Uncaught exception ‘Exception’ with message ‘Parameter can not be larger then 3!’ in C:wampwwwprivatcodeforestexceptionsindex.php:15 Stack trace: #0 C:wampwwwprivatcodeforestexceptionsindex.php(23): Generic->testValue(4) #1 {main} thrown in C:wampwwwprivatcodeforestexceptionsindex.php on line 15

Это произошло из-за отсутствия блока try-catch. Исправим ситуацию следующим образом:

try
{
    $gen = new Generic(3);
    $gen->testValue(4);
} catch (Exception $e) {
    // обработка исключения
    echo 'Поймали исключение<br />';
    echo 'Сообщение: '   . $e->getMessage() . '<br />';
    echo 'Дополнительный текст!';
}

Теперь мы успешно поймали наше исключение. Доказательство этому сообщение на экране.

Так же существует возможность получения детальной информации при перехвате исключительной ситуации. Это полезно тогда, когда у вас выбрасываются десятки или сотни исключений. Для того, чтобы быстро найти код, где это произошло, можно воспользоваться специальными методами:

try
  {
        $gen = new Generic(3);
        $gen->testValue(4);
  } catch (Exception $e) {
        // code to handle the Exception
        echo 'Error :' . $e->getMessage() . '<br />';
        echo 'Code :' . $e->getCode() . '<br />';
        echo 'File :' . $e->getFile() . '<br />';
        echo 'Line :' . $e->getLine() . '<br />';
        exit();
  }

Этот пример не сильно отличается от прошлого. Тут мы используем методы объекта, сгенерированного в блоке catch для получения более детальной информации об исключении, а именно само сообщение об ошибке, код ошибки (если такой имеется), файл и линия, где данное исключение было обработано.

Теперь в принципе вам должны быть ясны преимущества исключений. Обратите внимание на этот простой механизм, который может поможет вам отлавливать недочёты даже в самых “глубоких” местах. В добавок он даёт вам детальную информацию об ошибке, что позволит вам быстро всё исправить.

Вот ещё пример:

class Generic
{

    private   $someVar, $result;
    const     NUM_ERROR       = 1;
    const     ANY_ERROR       = 2; 

    public function __construct($someVar)
    {
        $this->someVar = $someVar;
    }

    public function testValue($someOtherVar)
    {
        if($someOtherVar > 3) {
            throw new Exception('Значение параметра не божет быть больше 3!', self::NUM_ERROR);
        } else {
            $this->result = $this->someVar + $someOtherVar;
            echo $this->result . '<br />';
        }
    }

    public function otherMethod()
    {
        if($this->result > 4) {
            throw new Exception('Результат больше 4.', self::ANY_ERROR);
        }
    }
}

// Начинаем охоту
try
{
      $gen = new Generic(3);
      $gen->testValue(2);
      $gen->otherMethod();
} catch (Exception $e) {
      if($e->getCode() == 1) {
          die ($e->getMessage());
      } else {
          echo 'Error :' . $e->getMessage() . '<br />';
          echo 'File :' . $e->getFile() . '<br />';
          echo 'Line :' . $e->getLine() . '<br />';
          exit();
      }
}

В этом новом примере я использую более сложную систему перехвата исключительных ситуаций, которые будут вызываться в зависимости от второго параметра, используемого в блоке CATCH. Это позволит вам создать систему ещё гибче в зависимости от выбрасываемого типа исключения.

Но это ещё не всё, что вы можете делать. Вы так же можете создавать свои типы исключений. В этом нет ничего сложного. Нам нужно просто создать дополнительный класс, который будет наследовать класс exception.

Кроме унаследованных методов, вы так же можете добавить и свои. Вот пример:

class Generic
  {

      private   $someVar, $result;
      const     NUM_ERROR       = 1;
      const     ANY_ERROR       = 2; 

      public function __construct($someVar)
      {
          $this->someVar = $someVar;
      }

      public function testValue($someOtherVar)
      {
          if($someOtherVar > 3) {
              throw new CustomException('Значение параметра не божет быть больше 3!', self::NUM_ERROR);
          } else {
              $this->result = $this->someVar + $someOtherVar;
              echo $this->result . '<br />';
          }
      }

      public function otherMethod()
      {
          if($this->result > 4) {
              throw new CustomException('Результат больше 4.', self::ANY_ERROR);
          }
      }
  }

  class CustomException extends Exception
  {

      public function logError()
      {
            // Записать в логи сервера
            if($this->getCode() == Generic::NUM_ERROR){
                error_log($this->getMessage(), 0);
            }
            // Сообщить админу по email
            else if($this->getCode() == Generic::ANY_ERROR){
                error_log($this->getMessage(), 1, 'sysadmin@domain.com');
            }
      }
}

  // Отлавливаем 
  try
  {
        $gen = new Generic(3);
        $gen->testValue(2);
        $gen->otherMethod();
  } catch (CustomException $e) {
        $e->logError();
  }

В этом примере мы создали наш собственный тип исключения CustomException.

При вызове logError() в зависимости от типа ошибки, будет осуществляться соответствующее действие (запись в логи или письмо админу).

В PHP5 существует метод set_exception_handler, который позволяет определить функцию перехватывающую все не отловленные исключения.

function myException($exception)
    {
        echo "<strong>Exception:</strong> " , $exception->getMessage();
    }

set_exception_handler('myException');

throw new Exception('Новое исключение');

PHP исключения это очень важный аспект, который должен использоваться в каждом крупном проекте. Многие PHP фрэймворки используют данную технику для регистрации всех ошибок, что позволяет быстро их устранить, тем самым строить настолько безопасные системы насколько это возможно.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Fatal error pci express
  • Fatal error pcap h no such file or directory
  • Fatal error ozzy batman arkham origins что делать
  • Fatal error out of memory вордпресс
  • Fatal error out of memory handler

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии