PHP curl返回代码200,即使该方法抛出代码400的异常

时间:2016-03-27 10:07:48

标签: php php-curl

我已经完成了API,现在我尝试使用curl方法拨打电话,并且我尝试输入错误数据以获取错误并检查所有工作情况。但是我不明白的是,当输入数据错误时,curl调用返回代码200,并且它会引发代码400的异常。

我的curl电话:

public function test() {

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL,"http://127.0.0.1/mysite/public/rest/createUser/");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, [
        "email" => "some.email",
        "address" => "elm street",
        "telephone" => "123123123",
    ]);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $server_output = curl_exec ($ch);

    curl_close ($ch);

    var_dump($server_output);

}

在这种情况下,电子邮件无效,并且在调用createUser方法并显示时会抛出异常。

{"error":"The email asd2123123 is invalid"}

代码是200而不是400

如果我拨打该网址而我没有使用curl方法,则会返回代码400

此外,我还使用Postman拨打电话,如果我直接拨打createUser并收到无效的电子邮件,则会返回代码400.

1 个答案:

答案 0 :(得分:1)

以这种方式尝试您的代码:

public function test() {

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL,"http://127.0.0.1/mysite/public/rest/createUser/");
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, [
        "email" => "some.email",
        "address" => "elm street",
        "telephone" => "123123123",
    ]);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, true);    // we want headers
    $server_output = curl_exec ($ch);

    curl_close ($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    echo 'HTTP code: ' . $httpcode;
    var_dump($server_output);
}

HTTP代码仍然是200吗?