Answer the question
In order to leave comments, you need to log in
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');
set_error_handler(function ($level, $message, $file = '', $line = 0)
{
throw new ErrorException($message, 0, $level, $file, $line);
});
Answer the question
In order to leave comments, you need to log in
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.Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question