所以我有一个简单的代码:
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的东西吗?
您可以从安装自己的错误处理开始。将PHP错误转换为异常的程序。在你的剧本开头做。像这样的东西:
/*
|--------------------------------------------------------------------------
| 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");
现在,您可以使用异常作为主要的错误处理机制。现在您所需要的就是在脚本中的正确位置捕获异常并自己显示错误。
您还可以扩展此机制以包括断言处理:
/*
|--------------------------------------------------------------------------
| 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++。这是一个前后矛盾的混乱局面。
您可以使用PHP的set_error_handler()
。
在要连接的调用前面放一个@符号。这将取消显示错误消息。