我有
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once "configuration.php";
header('Content-Type: application/json');
try
{
$mysqli = new mysqli(MYSQL_SERVER, MYSQL_USERNAME, MYSQL_PASSWORD, MYSQL_DATABASE);
$mysqli->set_charset("utf8");
} catch (Exception $e) {
echo json_encode(
array(
'msg' => $e->getMessage()
)
);
}
如果mysqli
没有启用,那么它不会捕获错误:
致命错误: Uncaught error: Class 'mysqli' not found in C:testdb_connect.php:8
堆栈跟踪:
#0 C:testgetContacts.php(2): require_once()
# 1}{主要在 C: test db_connect.php 8行
我怎么做才能捕获错误?
我试过这个,但它没有工作:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once "configuration.php";
header('Content-Type: application/json');
try
{
if(!extension_loaded('mysqli'))
{
throw new Exception('mysqli is not enabled');
}
$mysqli = new mysqli(MYSQL_SERVER, MYSQL_USERNAME, MYSQL_PASSWORD, MYSQL_DATABASE);
$mysqli->set_charset("utf8");
} catch (Exception $e) {
echo json_encode(
array(
'msg' => $e->getMessage()
)
);
}
不停止,继续执行脚本。
{"msg":"mysqli is not enabled"}
注意:未定义变量:mysqli in C:testgetContacts.php on line 99
致命错误: Uncaught错误:调用成员函数query()在null在C:testgetContacts.php:99堆栈跟踪:# 0{主要}C:testgetContacts.php on line 99
这是奇怪的,它不会被安装,但如果你自己滚动我想它可以省略。我将检查过程函数是否存在
if(!function_exists('mysqli_connect')) {
throw new Exception('mysqli is not enabled');
}
由于问题被标记为php-7
: php 7中的错误可以被捕获,但它不会从Exception
继承,因此您必须以不同的方式捕获它们:
...
} catch (Error $e) {
^^^^^ Not Exception
echo json_encode(
array(
'msg' => $e->getMessage()
)
);
// stop execution
exit;
}
有关php 7错误处理的更多信息,请参阅手册