抓住mysql连接错误 [英] Catching mysql connection error
问题描述
所以我有简单的代码:
try{
$mysqli = new mysqli($sql_login['host'], $sql_login['user'], $sql_login['password'] , $sql_login['database'], $sql_login['port'] );
if($mysqli->connect_errno){
throw new Exception("Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error);
}
}
catch (Exception $e) {
echo 'Exception: ', $e->getMessage(), "\n";
}
问题是php返回错误,也是异常。有没有像java中的throw和throws那样的东西?
the problem is that php returns error and also the exception. Is there something like in java with throw and throws?
推荐答案
您可以从安装自己的错误处理开始。将PHP错误转换为异常。在脚本开始时执行有些喜欢这样:
You can start with installing your own error-handling. One that converts PHP errors into exception. Do it at the beginning of your script. Something likes this:
/*
|--------------------------------------------------------------------------
| Alternative error handler
|--------------------------------------------------------------------------
|
| See: http://php.net/manual/en/function.set-error-handler.php
|
*/
function my_error_handler($errno, $errstr, $errfile, $errline)
{
if (!(error_reporting() & $errno))
{
// This error code is not included in error_reporting
return;
}
throw new ErrorException( $errstr, $errno, 0, $errfile, $errline );
}
ini_set('display_errors', FALSE);
set_error_handler("my_error_handler");
现在您可以使用异常作为主要的错误处理机制。所有你现在需要的是在脚本中的正确位置捕获异常,并自己显示错误。
Now you can use exceptions as the main error-handling mechanism. All you need now, is to catch the exceptions at the right location in your script and display errors yourself.
您可以扩展此机制以包括assert-handling:
You can extend this mechanism to include the assert-handling also:
/*
|--------------------------------------------------------------------------
| Assert handling
|--------------------------------------------------------------------------
|
| See: http://php.net/manual/en/function.assert.php
|
*/
function my_assert_handler($file, $line, $code)
{
throw new Exception( "assertion failed @$file::$line($code)" );
}
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_BAIL, 0);
assert_options(ASSERT_QUIET_EVAL, 0);
assert_options(ASSERT_CALLBACK, 'my_assert_handler');
只是接受PHP不是Java或C ++。这是一个不一致的混乱。
And just accept PHP is not Java or C++. It is a inconsistent mess.
这篇关于抓住mysql连接错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!