无法处理' getaddrinfo失败'

时间:2017-10-24 18:35:07

标签: php mysqli

我有一个连接数据库的PHP应用程序。

用户提供连接详细信息(主机名,用户名,密码等)。问题是当用户输入一个不存在的主机名时,我收到以下警告:

  

警告:mysqli :: mysqli():php_network_getaddresses:getaddrinfo   失败

如何处理此错误?我已经在使用try-catch,它完全处理其他异常(错误的用户名或密码),但不是这个。

这是我的代码:

backend.php

<?php
// Library setup
require_once "instlib.php";
$lib = new installer;

// Header
header('Content-Type: application/json; Charset=UTF-8');

try {
    $lib->create_mysqli(array(
        "host" => "a",
        "user" => "b",
        "pass" => "c",
        "database" => "",
        "port" => "3306"
    ));
    echo $lib->build_response("AWESOME!", true);
} catch (Exception $e) {
    echo $lib->build_response($e->getMessage(), false);
}
?>

instlib.php

<?php
require_once 'library.php';
class installer extends nncms
{   
    public function build_response($response = "", $success, $extra = array())
    {
        return json_encode(array_merge(array('success' => $success, 'response' => $response),$extra));
    }
}
?>

library.php

<?php
class nncms
{   
    var $mysqli;

    public function create_mysqli($config)
    {
        // Set MySQLi to throw expection instead of warning
        mysqli_report(MYSQLI_REPORT_STRICT);

        // Connection setup
        $mysqli = new mysqli(
            $config["host"],
            $config["user"],
            $config["pass"],
            $config["database"],
            $config["port"]
        );
        $mysqli->set_charset('utf8mb4');

        // In case of an error that somehow didn't throw an exception
        if ($mysqli->connect_errno)
            throw new Exception("Connection error: ".$mysqli->connect_error);

        // Set MySQLi object of class
        $this->mysqli = $mysqli;
    }
}
?>

1 个答案:

答案 0 :(得分:1)

要在Warning之后更改PHP的行为,有几个选项。

第一个选项,使用error suppressor operator @您不想这样做。它可以正常工作,但是当你无法找到你遇到的错误的原因时,它会给你带来问题。

if ($db = @mysqli_connect("a", "a", "a", "a")) {
    // connected
}

更好的选择是在遇到ErrorException时使用set_error_handler()投放Warning。这样您就可以优雅地处理错误Exception s:

function errorHandler($errno, $errstr, $errfile, $errline) {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("errorHandler");
try {
    if ($db = mysqli_connect("a", "a", "a", "a")) {
        // connected
    }
}
catch(ErrorException $e) {
    echo "Exception: ".$e->getMessage();
}