Introduction détaillée à la gestion des erreurs d'exception en PHP

王林
Libérer: 2023-04-07 09:06:02
avant
1929 Les gens l'ont consulté

1. Niveau de rapport d'erreurs error_reporting()

error_reporting(int $level);
Copier après la connexion

PHP 5.4 et supérieur E_ALL inclut E_STRICT.

Manuel PHP Tous les niveaux d'erreur.

Exemple :

<?php

// 关闭所有PHP错误报告
error_reporting(0);

// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);

// 报告 E_NOTICE也挺好 (报告未初始化的变量
// 或者捕获变量名的错误拼写)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// 除了 E_NOTICE,报告其他所有错误
error_reporting(E_ALL ^ E_NOTICE);

// 报告所有 PHP 错误 (参见 changelog)
error_reporting(E_ALL);

// 报告所有 PHP 错误
error_reporting(-1);

// 和 error_reporting(E_ALL); 一样
ini_set(&#39;error_reporting&#39;, E_ALL);

?>
Copier après la connexion

2. Fonction de gestion des erreurs set_error_handler()

set_error_handler(function (int $errno, string $errstr, string $errfile, int $errline) {
    // ...
}, $error_types = E_ALL)
Copier après la connexion

spécifiée par le $ ci-dessus error_types Le type d'erreur sera intercepté par la fonction de gestion des erreurs (sauf si la fonction renvoie false)

Lorsqu'une erreur se produit dans une instruction préfixée par @, la valeur $errno est 0

Le script continuera à s'exécuter après la fin de la fonction de traitement (vous devez donc appeler activement die() si nécessaire)

Exemple :

function handleError($level, $message, $file = &#39;&#39;, $line = 0)
{
    if (error_reporting() & $level) {
        throw new ErrorException($message, 0, $level, $file, $line);
    }
    return false;
}
Copier après la connexion

Convertir les exceptions d'erreur

Remarque : erreurs incapables

Le niveau d'erreur suivant ne peut pas être défini par l'utilisateur Fonction à traiter :

E_ERROR

<code><strong><span style="font-size: 14px;">E_PARSE</span></strong>

E_PARSE

<strong><span style="font-size: 14px;">E_CORE_ERROR</span></strong>

<code><strong><span style="font-size: 14px;">E_CORE_WARNING</span></strong>E_CORE_ERROR<span style="font-size: 14px;"></span>

<p id="1-错误报告级别-errorreporting" style="box-sizing: border-box; outline: 0px; margin: 8px 0px 16px; padding: 0px; font-size: 28px; font-family: "Microsoft YaHei", "SF Pro Display", Roboto, Noto, Arial, "PingFang SC", sans-serif; color: rgb(79, 79, 79); line-height: 36px; overflow-wrap: break-word; font-variant-ligatures: common-ligatures; white-space: normal; background-color: rgb(255, 255, 255);"><code><strong><span style="font-size: 14px;">E_COMPILE_ERROR</span></strong>E_CORE_WARNING

<strong><span style="font-size: 14px;">E_COMPILE_WARNING</span></strong>

set_error_handler() </span></strong>E_COMPILE_ERROR</p><p id="1-错误报告级别-errorreporting" style="box-sizing: border-box; outline: 0px; margin: 8px 0px 16px; padding: 0px; font-size: 28px; font-family: "Microsoft YaHei", "SF Pro Display", Roboto, Noto, Arial, "PingFang SC", sans-serif; color: rgb(79, 79, 79); line-height: 36px; overflow-wrap: break-word; font-variant-ligatures: common-ligatures; white-space: normal; background-color: rgb(255, 255, 255);"></span></strong>E_COMPILE_WARNING </p><p id="1-错误报告级别-errorreporting" style="box-sizing: border-box; outline: 0px; margin: 8px 0px 16px; padding: 0px; font-size: 28px; font-family: "Microsoft YaHei", "SF Pro Display", Roboto, Noto, Arial, "PingFang SC", sans-serif; color: rgb(79, 79, 79); line-height: 36px; overflow-wrap: break-word; font-variant-ligatures: common-ligatures; white-space: normal; background-color: rgb(255, 255, 255);"><span style="font-size: 14px;"></span>La plupart des E_STRICT générés dans le fichier où la fonction

est appelée. <🎜><🎜><🎜><🎜><🎜><🎜>Ces erreurs non détectées peuvent être gérées dans register_shutdown_function() (mais le script se terminera quand même) <🎜><🎜><🎜><🎜> <🎜 ><🎜><🎜><🎜><🎜>

3. 异常处理函数 set_exception_handler

// < PHP 7
set_exception_handler(&#39;handleException&#39;)


// < PHP 7
handleException(Exception $ex)
{
    echo "Uncaught exception: " , $ex->getMessage(), "\n";
}


// >= PHP 7
handleException(Throwable $ex)
{
    echo "Uncaught exception: " , $ex->getMessage(), "\n";
}
Copier après la connexion

<span style="font-size: 14px;"></span>

在用户自定义异常处理函数内部, 可根据情况做一下处理:

日志记录错误

web 渲染错误页面

console 渲染错误提示

<span style="font-size: 14px;"></span>

4. PHP 中止时执行函数

<span style="font-size: 14px;">register_shutdown_function</span>

register_shutdown_function(function () {

}, $para1, $param2, ...)
Copier après la connexion

在用户自定义脚本中止处理函数内部, 可根据情况做一下处理:

判断是否因严重错误而结束脚本(无法被 set_error_handler 捕获的错误中止脚本)

register_shutdown_function(&#39;handleShutdown&#39;)

function handleShutdown()
{
if (! is_null($error = error_get_last()) && isFatal($error[&#39;type&#39;])) {
      // handleException() 函数同时处理 set_exception_handler
      handleException(new \ErrorException(
        $error[&#39;message&#39;], $error[&#39;type&#39;], 0, $error[&#39;file&#39;], $error[&#39;line&#39;],
      ));
  }
}

function isFatal($type)
{
  return in_array($type, [E_COMPILE_ERROR, E_CORE_ERROR, E_ERROR, E_PARSE]);
}
Copier après la connexion

<span style="font-size: 14px;"></span>

以下错误无法被 set_error_handler 捕获

E_ERROR

E_PARSE

E_CORE_ERROR

E_CORE_WARNING

E_COMPILE_ERROR

E_COMPILE_WARNING

若因为错误而结束脚本, 若是严重错误则可将其转为 异常类, 并由异常处理函数统一处理.

Note:

多次调用 register_shutdown_function 时不会互相覆盖, 而是会按照注册顺序被依次调用.

除非在某个注册的方法内部调用 exit()

Note:

进程被信号 SIGTERMSIGKILL 杀死时中止函数不会被调用. 可通过 pcntl_signal 捕获信号, 再在其中调用 exit() 来进行正常中止。

以上就是关于错误异常的处理,如有错误请指出。不胜感激!

更多相关问题请访问PHP中文网:PHP视频教程


<span style="font-size: 14px;"></span>

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Étiquettes associées:
source:csdn.net
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!