简体   繁体   English

即使该方法引发代码400异常,PHP curl也会返回代码200

[英]PHP curl returns code 200 even though the method throws an exception with code 400

I've done an API and now I'm trying to make calls using the curl method and I'm trying to input bad data to get the errors and check all works well. 我已经完成了一个API,现在尝试使用curl方法进行调用,并且尝试输入错误的数据以获取错误并检查所有工作是否正常。 But what I don't understand is why the curl call returns the code 200 when the input data is wrong and it throws an exception with code 400. 但是我不明白的是,为什么在输入数据错误时curl调用会返回代码200,并引发代码400的异常。

That's my curl call: 那是我的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);

}

In that case the email is not valid and the exception is thrown when calling the createUser method and shows. 在这种情况下,电子邮件无效,并在调用createUser方法并显示时抛出异常。

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

And the code is 200 instead of 400 代码是200而不是400

If I call the URL and I don't use the curl method it returns the code 400 如果我调用该URL,但未使用curl方法,它将返回代码400

Also I'm using Postman to make the calls and it returns the code 400 if I call directly to createUser and I put an invalid e-mail. 另外,我使用Postman进行呼叫,如果直接调用createUser并放置了无效的电子邮件,它将返回代码400。

Try your code that way : 以这种方式尝试您的代码:

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);
}

Is the HTTP code still 200 ? HTTP代码仍然是200吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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