关于异常(Exception)的处理

<?php
declare(strict_types=1);
ini_set('display_errors', 'On');
error_reporting(-1);

/**
 * 异常(Exception)处理函数
 *
 * @param Exception $e Exception实例
 * @return void exit
 */
function exception(Exception $e): void
{
    $class = $e::class; // 获取异常类名,虽然形参是Exception类,但实际类型不一定和形参一致
    $message = $e->getMessage(); // 获取异常消息内容
    $file = $e->getFile(); // 获取发生异常的程序文件名称
    $line = $e->getLine(); // 获取发生异常的代码在文件中的行号
    $trace = $e->getTraceAsString(); // 获取异常追踪信息(即堆栈踪迹)

    // 仿照PHP错误报告格式显示异常信息(这里可以将异常信息写入错误日志文件或数据库,以方便开发人员修复错误)
    echo "$class: $message in $file on line $line, the exception trace is:" . PHP_EOL;
    echo $trace;

    exit;
}

$dsn = 'mysql:host=localhost;port=3306;dbname=test_db;charset=utf8mb4;';
$username = 'ZhangSan';
$password = '********';

try {
    $pdo = new PDO($dsn, $username, md5($password));
} catch (Exception $e) {
    exception($e);
    // PDOException: SQLSTATE[HY000] [1045] Access denied for user 'ZhangSan'@'localhost' (using password: YES) in /inetpub/wwwroot/demo/exception.php on line 32, the exception trace is:
    // #0 /inetpub/wwwroot/demo/exception.php(32): PDO->__construct()
    // #1 {main}
}


//========== 总结 ==========//
// 1、无论任何函数和方法,只要它会抛出异常,就应该使用try-catch将异常捕获,并将异常信息写入错误日志文件或数据库,
//    然后像修复Warning错误一样修复异常。

Copyright © 2024 码农人生. All Rights Reserved