简体   繁体   中英

Exception caught in try-catch, returned in ajax error state not success

I have a form with fields to connect to a database. This includes hostname, database, username and password. I am using an AJAX call to connect to the database. Some error handling needs to be taken care of, one of them is failing to connect to the database.

The exception is caught in a try-catch statement, I update the $result variable with the error message. This is then returned to the AJAX call.

Here is a simplified version of the code:

AJAX Call:

$.ajax({
    url: _url + 'dbv.php',
    type: 'POST',
    data: {
        db_host: $('input[name="db_host"]').val(),
        db_name: $('input[name="db_name"]').val(),
        db_username: $('input[name="db_username"]').val(),
        db_password: $('input[name="db_password"]').val(),
        save_path: $('input[name="save_path"]').val()
    },
    dataType: 'json',
    success: function(data) {
        if (data.error) {
            console.log('success (error): ' + JSON.stringify(data));
        }
        else {
            console.log('success: ' + JSON.stringify(data));
        }
    },
    error: function(data) {
        console.log('error: ' + JSON.stringify(data));
    }
});

PHP:

try {

    if ($_POST['db_host'] && $_POST['db_username'] && $_POST['db_password'] && $_POST['db_name'] && $_POST['save_path']):

        $host = $_POST['db_host'];
        $user = $_POST['db_username'];
        $password = $_POST['db_password'];
        $database = $_POST['db_name'];
        $path = $_POST['save_path'];

    else:

        throw new Exception('Empty Fields', '1');

    endif;

    if (!$result->error):

        $conn = new mysqli($host, $user, $password, $database);

        // ...

        mysqli_close($conn);

    endif;
}
catch (Exception $e) {
    $result->error = true;
    $result->message = 'Error: ' . $e->getMessage();
}

$result->message = (!$result->error) ? 'Successful' : $result->message;
echo json_encode($result);

The first exception in the code, Empty Fields , is caught and returned to the success function. The issue I'm having is that the error AJAX state is fired not when the database connection is incorrect. The returned data includes both PHP's default error message and the $result variable. Shouldn't this be just the $result variable, same as the Empty Fields Exception?

Screenshots of what's happening:

引发异常 捕获异常

Error responseText including both PHP's error and $result variable:

"responseText":

PHP's error:

" : mysqli::mysqli(): php_network_getaddresses: getaddrinfo failed: No such host is known. in on line :mysqli :: mysqli():php_network_getaddresses:getaddrinfo失败:在第行的没有此类主机已知。

$result variable:

{\\"error\\":true,\\"message\\":\\"Error: php_network_getaddresses: getaddrinfo failed: No such host is known. \\"}"

I've been searching quite a bit and it looks like the logic is fine - maybe there's something I'm completely missing.

Two examples similar to what I'm trying to do: https://stackoverflow.com/a/20938633/1275525 , https://stackoverflow.com/a/12693587/1275525

I see some solutions:

  1. [GOOD] Disable connect warnings and throw custom exception, to example https://stackoverflow.com/a/14049169/1559720
  2. [BAD] Bufferize output using ob_start

For first point, example:

@$mysql = new mysqli($host, $user, $password, $database);
if ($mysql->connect_errno) {
   throw new \Exception($mysql->connect_error, $mysql->connect_errno);
}

host name must be: localhost . I don't think getaddrinfo it's your host. What is getaddrinfo ?

When you catch an error you do

catch (Exception $e) {
    $result->error = true;

this means that the result that gets returned contains the info 'my error property is true' so that's why your javascript then thinks that there is an error. To reverse this behaviour you can simply omit that last line.

However, why would you want this? It seems logical for your javascript to do something different when there is an error. Like notifying the user for example.

This bit also seems a bit strange to me:

success: function(data) {
    if (data.error) {
        console.log('success (error): ' + JSON.stringify(data));
    }
    else {
        console.log('success: ' + JSON.stringify(data));
    }

As there's already a different function for success and error why would you then check for errors in the success function? This function should never even be triggered when there's an error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM