douxun4860 2016-05-01 15:52
浏览 53

在php中捕获错误并将其作为json返回给html

is it possible to catch error in a php file, lets say in the connection section, and return it to the HTML file as json for printing.

This is my try:

<?php
    $srevernme = "localhost";
    $username = "root";
    $password = "";
    $dbname = "db";

    //create connection
    $conn = new mysqli($srevernme,$username,$password,$dbname);

    $errors = array();  // array to hold connection errors

    //check connection                                              //<-----POSSIBLE ERROR
    if ($conn->connect_error) {
         $data['success'] = false;
         $errors['error_info'] = "connection failed:" . $conn->connect_error ."Please try later.";
         $data['errors'] = $errors;
         echo json_encode($data);
        //die("connection failed:" . $conn->connect_error);
    }



if ($_SERVER['REQUEST_METHOD'] == "POST") 
    {        
        if (isset($_POST["fnameInput"]) && isset($_POST["lnameInput"]) && isset($_POST["addressInput"]) && isset($_POST["cityInput"]) && isset($_POST["zipcodeInput"]))
        {
            // prepare and bind
            $stmt = $conn->prepare("INSERT INTO users (first_name, last_name) VALUES (?, ?)");

            if ($stmt == FALSE) {                                       //<-----POSSIBLE ERROR          
                $data['success'] = false;
                $errors['error_info'] = "Connection failed: Cannot create connection to sql DB. Please try later.";
                $data['errors'] = $errors;
                echo json_encode($data);
                //die("Connection failed: Cannot create connection to sql DB. Please try later.");
                }

           if (empty($errors)) 
           { 
                    //mark as success
                    $data = array(); //array for saving the data
                    $data['success'] = true;

                    //get wanted data....

                   $data['wanted_data'] = json_encode($some_data);
                   echo json_encode($data);

                   $stmt->close();
            }
    }
    $conn->close();

The relevant sections are marked with //<-----POSSIBLE ERROR. To be clear- data represents the data I want to echo to the html file and it had a key named success that his values are true if everything is ok or false if there is an error.

EDIT: In the current state the php file send request in this format when I shot down MySQL server (from chrome inspector):

<br />
<b>Warning</b>:  mysqli::mysqli():  in <b>C:\xampp\htdocs\projectegister.php</b> on line <b>7</b><br />
<br />
<b>Warning</b>:  mysqli::prepare(): Couldn't fetch mysqli in <b>C:\xampp\htdocs\ex3egister.php</b> on line <b>26</b><br />
{"success":false,"error_info":"Connection failed: Cannot create connection to sql DB. Please try later."}<br />
<b>Fatal error</b>:  Call to a member function bind_param() on null in <b>C:\xampp\htdocs\ex3egister.php</b> on line <b>39</b><br />

Thanks!

  • 写回答

1条回答 默认 最新

  • doujiu6976 2016-05-01 16:04
    关注

    Ohh, is that what you mean?

    It seems the JSON arrives just fine. What you mean is to disable php errors? In this case, you can turn off php's standard error reporting, so it only shows your custom errors. (Note that this means you will not get an error that you aren't manually taking care of)

    see http://php.net/manual/en/function.error-reporting.php for more information.

    // Turn off all error reporting
    error_reporting(0);
    

    This will prevent php from echo-ing its own errors, thus only returning your (valid) json_encoded errors.

    edit: You'll want to return json_encode($errors) instead of json_encode($data) in case of an error.

    edit#2: I would really advise you to not return anything until you've reached the end of your script, so it's less confusing. Simply put an if statement at the end.

    if(!empty($errors)){
     echo json_encode($errors);
     return false; //don't go on
    }
    else{
     echo json_encode($data);
     return false; //don't go on
    }
    

    In case of an error, simply add to the $errors array, as it seems to me that's what you're wanting to do in the first place.

    评论

报告相同问题?

悬赏问题

  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法