如何将异常从 PHP 抛出到 Angular $http 服务


how to throw an exception from php to angular $http service

我正在用AngularJS写博客,我使用php生成一个包含数据库中数据的json。我的角度"获取文章"函数看起来像这样

$scope.getDetail = function() {
        $http.get('php/blogGetArticle.php?id=2').success(function(json) {
            $scope.jsonDetail = json;
            alert('ok');
        }).error(function() {
            alert('error');
        });
    };

我的php'blogGetArticle.php'看起来像这样。

<?php
    $id = $_GET['id'];
    $dbhost = "localhost";
    $dbport = "5432";
    $dbname = "pd";
    $dbuser = "postgres";
    $dbpass = "123";
    $connect = pg_connect("host=" . $dbhost . " port=" . $dbport . " dbname=" . $dbname . " user=" . $dbuser . " password=" . $dbpass);
    if(!$connect)
        die("error 0"); // connect error
    $query = "SELECT * FROM blog WHERE id=" . $id;
    $result = pg_query($connect, $query);
    if(!$result)
        die('error 1'); // query error
    $row = pg_fetch_row($result);
    $json = '{';
    $json .= '"id":"' . addslashes($row[0]) . '",';
    $json .= '"title":"' . addslashes($row[1]) . '",';
    $json .= '"message":"' . addslashes($row[2]) . '",';
    $json .= '"category":"' . addslashes($row[4]) . '"';
    $json .= '}';
    echo $json;
?>

现在我试图做的是,当我在php中调用某些东西时,我尝试使角度函数进入.error分支.我不知道如何解释。例如,当我在 php 中有一个小于 10 的 id 时,我希望角度函数抛出异常,但我想从 php 文件将其抛出该异常到角度函数。

谢谢你,丹尼尔!

编辑:那么我如何抛出 4xx 或 5xx 错误?

PHP:

try {
} catch (Exception $e) {
    header("HTTP/1.1 500 Internal Server Error");
    echo '{"data": "Exception occurred: '.$e->getMessage().'"}';
}

AngularJS

        , function(error) {
          $log.error('Error message: '+error.data);
        }); 

你可以这样做

  if(!$connect)
      // or may be code 500
       header("HTTP/1.0 404 Not Found");
       exit; 
$query = "SELECT * FROM blog WHERE id=" . $id;
$result = pg_query($connect, $query);
if(!$result)
    header("HTTP/1.0 404 Not Found");
    exit;

我建议您尝试 http://us.php.net/manual/en/function.json-encode.php,不要再费力:)

再见

你不能用不同的格式返回 json 吗?

if(!$result){
    $json = '{';
    $json .= '"error":"failed loading data",';
    $json .= '}';
}else{
    $row = pg_fetch_row($result);
    $json = '{';
    $json .= '"id":"' . addslashes($row[0]) . '",';
    $json .= '"title":"' . addslashes($row[1]) . '",';
    $json .= '"message":"' . addslashes($row[2]) . '",';
    $json .= '"category":"' . addslashes($row[4]) . '"';
    $json .= '}';
}
echo $json;

然后在角度检测 json 中是否存在错误,然后您可以计划多个错误与进程状态结果调用。

jsonObj.hasOwnProperty("error")