如何在PHP中确定异常来自哪一行的代码

4

我即将完成一个项目,但是在我的error_log文件中注意到了出现了错误。每当我加载index.php文件时,就会收到这个错误,并且在一次重新加载中,我会得到21行错误代码。

我已经尝试从header.php文件进行调试,最疯狂的事情是,在我调用header.php文件之前,我没有任何错误,但是当我在index.php文件中调用header.php时,我就会遇到错误。因此,我尝试通过PDO的trycatch来捕获错误。在error log文件中,我获取到了错误消息,因此我将我的代码从这个样子:Select Query: ".$e->getMessage() 改为 Select Query: ".$e->getFile()Select Query: ".$e->getLine()。但是这样做我只能得到错误所在的行号,而不是它被抛出的那一行。

我认为我在databse.php文件中的select查询中存在问题。以下是我的select查询代码:

final protected function select($args = array(), $is_die = false){
            try {

        $this->sql = "SELECT ";
        if (isset($args['fields'])) {
            if (is_array($args['fields'])) {
                $this->sql .= implode(', ', $args['fields']);
            } else {
                $this->sql .= $args['fields'];
            }
        } else {
            $this->sql .= " * ";
        }
        $this->sql .= " FROM ";
        if (!isset($this->table) || empty($this->table)) {
            throw new Exception("Table not set");
        }
        $this->sql .= $this->table;

        /*Join Query*/
        if (isset($args['join']) && !empty($args['join'])) {
            $this->sql .= " ".$args['join'];
        }
        /*Join Query*/

        if (isset($args['where']) && !empty($args['where'])) {
            if (is_array($args['where'])) {
                $temp = array();
                foreach ($args['where'] as $column_name => $data) {
                    if (!is_array($data)) {
                        $data = array(
                            'value'     => $data,
                            'operator'  => '=',
                        );
                    }
                    $str = $column_name.' '.$data['operator'].' :'.str_replace('.', '_', $column_name);
                    $temp[] = $str;
                }
                $this->sql .= " WHERE ".implode(' AND ', $temp);
            } else {
                $this->sql .= " WHERE ".$args['where'];
            }
        }

        /*Group*/
        if (isset($args['group_by']) && !empty($args['group_by'])) {
            $this->sql .= " GROUP BY ".$args['group_by'];
        }
        /*Group*/

        /*Order*/
        if (isset($args['order_by']) && !empty($args['order_by'])) {
            $this->sql .= " ORDER BY ".$args['order_by'];
        } else {
            $this->sql .= " ORDER BY ".$this->table.".id DESC";
        }
        /*Order*/

        /*Limit*/
        if (isset($args['limit']) && !empty($args['limit'])) {
            if (is_array($args['limit'])) {
                $this->sql .= " LIMIT ".$args['limit'][0].",".$args['limit'][1];
            } else {
                $this->sql .= " LIMIT ".$args['limit'];
            }
        }
        /*Limit*/
        $this->stmt = $this->conn->prepare($this->sql);
        if (is_array($args['where']) || is_object($args['where'])){

            foreach ($args['where'] as $column_name => $data) {
            $value = is_array($data) ? $data['value'] : $data; //check if passed where statement was an array, fetch value if so
            if (is_int($value)) {
                $param = PDO::PARAM_INT;
            }elseif (is_bool($value)) {
                $param = PDO::PARAM_BOOL;
            }elseif (is_null($value)) {
                $param = PDO::PARAM_NULL;
            }else {
                $param = PDO::PARAM_STR;
            }
            if ($param) {
                $this->stmt->bindValue(":".str_replace('.', '_', $column_name), $value, $param);
            }
        }

        }

        if ($is_die) {
            echo $this->sql;
            debugger($this->stmt);
            debugger($args, true);
        }

        $this->stmt->execute();
        $data = $this->stmt->fetchAll(PDO::FETCH_OBJ);
        return $data;
        } catch (PDOException $e) {

                error_log(
                    date('Y-m-d h:i:s A').", Select Query: ".$e->getMessage()."\r\n"
                    , 3, ERROR_PATH.'/error.log');
                return false;
            } catch (Exception $e) {
                error_log(
                    date('Y-m-d h:i:s A').", General: ".$e->getMessage()."\r\n"
                    , 3, ERROR_PATH.'/error.log');
                return false;
            }
    }

有没有可能通过try catch或其他方式获取文件中抛出错误的行号?

2个回答

3
你可以使用trycatch语句来捕获异常,对于行号则可以使用__LINE__
例如:
try {
  /* Your Code */
} catch (Exception $e) {
   echo __LINE__.$e->getMessage() "\n";
}

在你的代码中,处理异常的部分应当这样写:
"Line No : " __LINE__.date('Y-m-d h:i:s A')

要获取行号和文件路径,请使用以下内容

"Line No : " __LINE__." : File Path : ".__FILE__.date('Y-m-d h:i:s A')

我应该把这段代码粘贴到哪里?我什么也没得到。 - Alisha Lamichhane
它给了我行号,我也找到了行号,但是文件名呢?因为当我检查index.php、header.php和menu.php的第152行时,并没有在那一行找到任何php代码。 - Alisha Lamichhane
@Alisha,我已经包含了文件名,请查看更新的答案。 - Rakesh Jakhar
4
这段代码产生的输出与 $e->getFile() 和 $e->getLine() 相同。 - Alisha Lamichhane
@Alisha 最好使用 $e->getFile() 和 $e->getLine(),如果这些方法在对象 $e 中存在的话。你可以通过 print_r(get_class_methods($e)) 查看 $e 的所有方法。 - Rakesh Jakhar

0

我刚刚粘贴了一段代码,以获取我的选择查询中的行号和函数名称。

以下是代码:

Exception("MySQL error $mysqli->error <br> Query:<br> $sql", $msqli->errno);

在添加上述代码行后,选择查询将如下所示:

final protected function select($args = array(), $is_die = false){
        try {

    $this->sql = "SELECT ";
    if (isset($args['fields'])) {
        if (is_array($args['fields'])) {
            $this->sql .= implode(', ', $args['fields']);
        } else {
            $this->sql .= $args['fields'];
        }
    } else {
        $this->sql .= " * ";
    }
    $this->sql .= " FROM ";
    if (!isset($this->table) || empty($this->table)) {
        throw new Exception("Table not set");
    }
    $this->sql .= $this->table;

    /*Join Query*/
    if (isset($args['join']) && !empty($args['join'])) {
        $this->sql .= " ".$args['join'];
    }
    /*Join Query*/

    if (isset($args['where']) && !empty($args['where'])) {
        if (is_array($args['where'])) {
            $temp = array();
            foreach ($args['where'] as $column_name => $data) {
                if (!is_array($data)) {
                    $data = array(
                        'value'     => $data,
                        'operator'  => '=',
                    );
                }
                $str = $column_name.' '.$data['operator'].' :'.str_replace('.', '_', $column_name);
                $temp[] = $str;
            }
            $this->sql .= " WHERE ".implode(' AND ', $temp);
        } else {
            $this->sql .= " WHERE ".$args['where'];
        }
    }

    /*Group*/
    if (isset($args['group_by']) && !empty($args['group_by'])) {
        $this->sql .= " GROUP BY ".$args['group_by'];
    }
    /*Group*/

    /*Order*/
    if (isset($args['order_by']) && !empty($args['order_by'])) {
        $this->sql .= " ORDER BY ".$args['order_by'];
    } else {
        $this->sql .= " ORDER BY ".$this->table.".id DESC";
    }
    /*Order*/

    /*Limit*/
    if (isset($args['limit']) && !empty($args['limit'])) {
        if (is_array($args['limit'])) {
            $this->sql .= " LIMIT ".$args['limit'][0].",".$args['limit'][1];
        } else {
            $this->sql .= " LIMIT ".$args['limit'];
        }
    }
    /*Limit*/
    $this->stmt = $this->conn->prepare($this->sql);
    if (is_array($args['where']) || is_object($args['where'])){

        foreach ($args['where'] as $column_name => $data) {
        $value = is_array($data) ? $data['value'] : $data; //check if passed where statement was an array, fetch value if so
        if (is_int($value)) {
            $param = PDO::PARAM_INT;
        }elseif (is_bool($value)) {
            $param = PDO::PARAM_BOOL;
        }elseif (is_null($value)) {
            $param = PDO::PARAM_NULL;
        }else {
            $param = PDO::PARAM_STR;
        }
        if ($param) {
            $this->stmt->bindValue(":".str_replace('.', '_', $column_name), $value, $param);
        }
    }

    }

    if ($is_die) {
        echo $this->sql;
        debugger($this->stmt);
        debugger($args, true);
    }

    $this->stmt->execute();
    $data = $this->stmt->fetchAll(PDO::FETCH_OBJ);
    return $data;
    } catch (PDOException $e) {

            error_log(
                date('Y-m-d h:i:s A').", Select Query: ".$e->getMessage()."\r\n"
                , 3, ERROR_PATH.'/error.log');
            return false;
        } catch (Exception $e) {
            error_log(
                date('Y-m-d h:i:s A').", General: ".$e->getMessage()."\r\n"
                , 3, ERROR_PATH.'/error.log');
                Exception("MySQL error $mysqli->error <br> Query:<br> $sql", $msqli->errno);
            return false;
        }
}

有关更多信息,程序员可以访问此链接: PHP手册


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接