A
A
Alexey2020-10-22 17:39:23
PHP
Alexey, 2020-10-22 17:39:23

Am I understanding PHP's centralized exception handling correctly?

Hello!

I'm trying to figure out how to properly handle exceptions in a web application .. so far I've settled on this option. Are there any cons, maybe it's better in another way?

The code below is placed in a file like error-handler.php and included on all the necessary pages.

// Файл error-handler.php
// Централизованная обработка исключений

ini_set("log_errors", 1);
ini_set("error_log", __DIR__ . "/php-errors.log");

// Уровень ошибок display_errors = 1 используется во время разработки,
// на рабочем сервере установить на 0
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL & ~E_NOTICE);

// Обрабатываем все исключения, возникающие во время работы приложения
function customExceptionHandler($e)
{
    error_log($e);
    http_response_code(500);
    // Если в режиме отладки, то показываем исключения
    if (ini_get('display_errors')) {
        echo $e;
    } else {
        echo "<h1>500 Ошибка сервера.</h1>
              Произошла ошибка на стороне сервера.<br>
              Пожалуйста, попробуйте еще раз позже.";
    }

}

set_exception_handler('customExceptionHandler');


Those. in customExceptionHandler we catch all possible exceptions and take appropriate action.

Sometimes there are errors (Error), not exceptions, then they suggest adding such code, is it worth it?

set_error_handler(function ($level, $message, $file = '', $line = 0)
{
    throw new ErrorException($message, 0, $level, $file, $line);
});


Those. we change the error to an exception, and we are already processing it again in our customExceptionHandler.

I will be grateful for any comments)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
FanatPHP, 2020-10-22
@Allexio

In general, right, a good study of the material .
I have only a couple of comments that are not directly related to the centralized handler.

  • error_reporting(E_ALL & ~E_NOTICE);not worth doing . Unless you have to work with a hell of a legacy that pours notes, it's better to catch all errors. Considering that in 8-ke access to a non-existent variable will not become a notice, but a warning, such a construction will eventually become meaningless. which means that mistakes should be corrected, not hushed up.
  • ini_set("error_log", __DIR__ . "/php-errors.log");it would not be a good idea if the error-handler.php file is above the web server root. Mistakes should be hidden away.
  • ini_set('display_startup_errors', 1);- this is some kind of game that wanders from leadership to leadership. No one has ever seen these startup errors, but many diligently write this spell in their code. This is in any way related to setting up the server, and will help in debugging errors in about nothing.
  • by itself, setting settings via ini-set is unreliable. An error may occur before PHP reads this command. It must be set in the web server configuration.
  • in theory, you can add a flag or automatic check for jason's request. and encode the response in jason accordingly. But this is only for cryo-handed frontenders who can't read HTTP statuses, but are waiting for everything to be chewed on in jason, and without error: true they won't understand that there was an error
  • the call stack can be quite long, and bloat the logs. You can think of a shorter version.

In general, it all depends on the tasks. For example, all modern frameworks in development mode give out a spreading page with an error report, which also includes a piece of code around the build on which the error occurred.
But as a basic handler, the minimum required is quite good.
I just did not understand why the question is about error_handler. What exactly is confusing?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question