dragon88112
2012-08-06 10:38 阅读 45
已采纳

捕获mysql连接错误

So i have simple code:

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(), "
";
}

the problem is that php returns error and also the exception. Is there something like in java with throw and throws?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

3条回答 默认 最新

  • 已采纳
    douzhanjia0773 douzhanjia0773 2012-08-06 11:41

    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.

    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');
    

    And just accept PHP is not Java or C++. It is a inconsistent mess.

    点赞 评论 复制链接分享
  • douge3830 douge3830 2012-08-06 11:24

    You can use PHP's set_error_handler().

    点赞 评论 复制链接分享
  • douzhan1935 douzhan1935 2012-08-06 11:29

    Put an @ sign in front of the call to connect. That will suppress the error message.

    点赞 评论 复制链接分享

相关推荐