Write a class for processing of PHP errors. Code example open

Write a class for processing of PHP errors. Code example

Approved. Code works!
This is exactly the working code that is verified by the moderator or site administrators
Tested: PHP 7

Error handling is the process of detecting errors caused by your program and then taking appropriate action. If you handle errors correctly, this can lead to many unforeseen consequences.

In the core of our framework (folder vendor/core) create a new file errorcatcher.php and add the following code:

//use the namespace
namespace core;

//create a new class
class ErrorCatcher
{

    public function __construct()
    {
      
        if (DEBUG) {//constant in the init.php file in which DEBAG is specified - true, false
            error_reporting(-1);//if true enables error display mode
        } else {
            error_reporting(0);//false error display mode is disabled
        }

        set_exception_handler([$this, 'exceptionHandler']);//creates custom exception handling. Takes in the callback method exceptionHandler
        set_error_handler([$this, 'errorHandler']);//creates custom error handling. Takes in the callback method errorHandler
        ob_start();//turn on buffering so that the error is filled but not displayed
        register_shutdown_function([$this, 'fatalErrorHandler']);//method for handling fatal errors
    }

    public function errorHandler($errno, $errstr, $errfile, $errline)
    {
        $this->logError($errstr, $errfile, $errline);
        $this->displayError($errno, $errstr, $errfile, $errline);
    }

    public function fatalErrorHandler()
    {
        $fatal_error = error_get_last();//write the last fatal error in the variable
        if (!empty($fatal_error) && $fatal_error['type'] & (E_ERROR | E_PARSE | E_COMPILE_ERROR | E_CORE_ERROR)) {
            $this->logError($fatal_error['message'], $fatal_error['file'], $fatal_error['line']);
            ob_end_clean();
            $this->displayError($error['type'], $error['message'], $error['file'], $error['line']);
        } else {
            ob_end_flush();
        }
    }

    
    public function exceptionHandler(\Throwable $e)//inherit the interface. The $ e object will contain all the error information
    {
        $this->logError($e->getMessage(), $e->getFile(), $e->getLine());// upon receipt of the error, log it into a file. To do this, pass the error information to the logError method parameters

        $this->displayError('Exception', $e->getMessage(), $e->getFile(), $e->getLine(), $e->getCode());//// when you receive an error, display it. To do this, pass the error information to the displayError method
    }

    //method for logging errors to the errors.log file
    protected function logError($message = '', $file = '', $line = '')
    {
        file_put_contents(
            LOGS . '/error.log',//a place to write down our errors. The LOGS constant specifies the address of the log directory
            "[" . date('Y-m-d H:i:s') . "] Text: {$message} | file: {$file} | in line: {$line}",//text with our error data
            FILE_APPEND);//add  to the end of file
    }

    //method for error output
    protected function displayError($errno, $errstr, $errfile, $errline, $responce = 500)
    {
        if ($responce == 0) {//if error code 0 is set to 404
            $responce = 404;
        }

        http_response_code($responce);//send the response code in the header

        if ($responce == 404 && !DEBUG) {//if error code is 404 and debug mode is enabled
            require_once WWW . '/errors/404.php';//print page 404 which is in the folder public/errors
            die;
        }
        if (DEBUG) {//if debug is enabled
            require WWW . '/errors/development.php';//connect the file development.php 'which will contain detailed information about the error
        } else {
            require WWW . '/errors/production.php';//page that will give information that the site is now a technical error
        }
        die;
    }

}

As you can see in the last step we created 3 new pages:

/errors/404.php – will be displayed when a 404 error code occurs
/errors/development.php – will be displayed when an error occurs and DEBUG mode is enabled
/errors/production.php – will be displayed when an error occurs and DEBUG mode is disabled

You can fill in these pages as you wish. For example, we will fill in the development page:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Error</title>
</head>
<body>

<p><b>Error code:</b> <?= $errno ?></p>
<p><b>Error message:</b> <?= $errstr ?></p>
<p><b>Error file:</b> <?= $errfile ?></p>
<p><b>Error line:</b> <?= $errline ?></p>

</body>
</html>

For our debugger to work, it must be initialized in the main App class adding it to __construct

public function __construct()
    {
        new ErrorCatcher();//an instance of our class that will catch exceptions and errors

        self::$app = Registry::getInstance();
        
        $this->getParams();
    }
0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation