0

I am building an API to store registered users data. Data is passed using CURL with an api-key. I need to check the api-key is valid or not. If it is not valid return an error message with an CURLINFO_HTTP_CODE. I returned the message. But the CURLINFO_HTTP_CODE is 200. I need to change it to 500. How to do that? I am using SLIM framework

Data Posting code.

private static function postJSON($url, $data) { 

    $jsonData = array (
      'json' => json_encode($data)
    ); // data array contains some data and api-key

    $jsonString = http_build_query($jsonData);
    $http = curl_init($url);

    curl_setopt($http, CURLOPT_HEADER, false);
    curl_setopt($http, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($http, CURLOPT_POST, true);
    curl_setopt($http, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
    curl_setopt($http, CURLOPT_HTTPHEADER, array(
      'Content-Type: application/x-www-form-urlencoded',
      'Content-Length: '.strlen($jsonString)
    ));
    curl_setopt($http, CURLOPT_POSTFIELDS, $jsonString);

    $responseBody = curl_exec($http); 
    $statusCode = curl_getinfo($http, CURLINFO_HTTP_CODE);
    echo $statusCode; // need to get 500 if the api key is not registerd

    if($statusCode > 200) {
        error_log('BugTracker Warning: Couldn\'t notify ('.$responseBody.')');
    } 
    curl_close($http); 

    return $statusCode;
}

Following is the code which will respond to the CURL operation

$apiKey = $event->apiKey;
    // Check if the project for the given api key exists. if not do not insert the bugs
    $projectDetails = $bt->getProjectDetails($apiKey);
    if(count($projectDetails)>0){
        print_r($projectDetails);
        foreach($event->exceptions as $bug){
            $errorClass = $bug->errorClass;
            $message    = $bug->message;
            $lineNo     = $bug->lineNo;
            $file       = $bug->File;
            $createdAt  = $bug->CreatedAt;

            //saving to db
            $bt->saveData($releaseStage,$context,$errorClass,$message,$lineNo,$file,$createdAt,$apiKey);
        }
    }
    else{
        // show error with 500 error code
        http_response_code(500);
        echo "Invalid project";
    }
4

2 に答える 2

1

あなたが探しているのは$app->halt(). 詳細については、Slim ドキュメントのRoute Helpersセクションを参照してください。

Slim アプリケーションのhalt()メソッドは、指定されたステータス コードと本文を含む HTTP 応答をすぐに返します。このメソッドは、HTTP ステータス コードとオプションのメッセージの 2 つの引数を受け取ります。

これにより、500 とメッセージを返すのは非常に簡単になりますが、サーバー エラー (5xx) ではなく、要求されたプロジェクトが見つからない (404) というメッセージを送信しようとしているため、代わりに使用$app->notFound()することを検討してください。 .

于 2013-12-12T14:53:59.440 に答える
0

ヘッダーを 500 に設定できます

header("HTTP/1.1 500 Internal Server Error");

または、try catch を使用してエラーをスローしてみてください

throw new Exception("This is not working", 500);
于 2013-10-22T02:11:36.773 に答える