2012-12-19 27 views
0

我正在編寫一個REST API並且正在測試一些東西。我試圖讓它在數據庫中找不到任何內容時發送錯誤響應。Easyuniv REST API爲什麼不能處理錯誤?

運行(因爲我只輸入網址進入我的瀏覽器目前正在測試)的部分是下面:

else if ($request->getHttpAccept() === 'xml') 
    { 
     if(isset($data['s']) && isset($data['n'])) { 
      $id = $db->getAlcoholIDByNameSize($data['n'], $data['s']); 
      $prices = $db->pricesByAlcohol($id); 
     } 
     if(isset($id)) { 
      $resData = array(); 
      if(!empty($prices)) { 
       foreach($prices as $p) { 
        $store = $db->store($p['store']); 
        array_push($resData, array('storeID' => $p['store'], 'store_name' => $store['name'], 'store_gps' => $store['gps'], 'price' => round($p['price'], 2))); 
       } 
       RestUtils::sendResponse(200, json_encode($resData), 'application/json'); 
      } else { 
       RestUtils::sendResponse(204, 'error', 'application/json'); 
      } 
     } else { 
      RestUtils::sendResponse(204, 'error', 'application/json'); 
     } 
     //RestUtils::sendResponse(501, "xml response not implemented", 'application/xml'); 
    } 

一切工作正常,如果查詢返回的東西存儲在$ ID和$價格。但是,如果它們不存在於數據庫中,它會嘗試加載頁面,然後返回到上一頁。你可以去看看的行爲:

http://easyuniv.com/API/alc/coorsa/2 <-- works 
http://easyuniv.com/API/alc/coors/3 <-- works 
http://easyuniv.com/API/alc/coorsa/5 <-- doesn't work(or anything else, the two above are the only ones) 

這裏是我的sendResponse功能:

public static function sendResponse($status = 200, $body = '', $content_type = 'text/html') 
    { 
     $status_header = 'HTTP/1.1 ' . $status . ' ' . RestUtils::getStatusCodeMessage($status); 
     // set the status 
     header($status_header); 
     // set the content type 
     header('Content-type: ' . $content_type); 

     // pages with body are easy 
     if($body !== '') 
     { 
      $temp = json_decode($body); 
      $body = json_encode(array('result' => array('status' => $status, 'message' => RestUtils::getStatusCodeMessage($status)), 'data' => $temp)); 
      // send the body 
      echo $body; 
      exit; 
     } 
     // we need to create the body if none is passed 
     else 
     {   
      $body = "else".json_encode(array('result' => array('status' => $status, 'message' => RestUtils::getStatusCodeMessage($status)))); 

      echo $body; 
      exit; 
     } 
    } 

我曾嘗試使用回聲調試,但我似乎無法縮小問題的範圍是什麼。任何幫助將不勝感激,謝謝。

+0

這可能不是編程相關的,但只是對您使用的REST框架的一些支持請求。您是否與軟件供應商聯繫瞭解您的問題?他們回覆了什麼? – hakre

+0

我寫了api,第一個代碼塊是處理我正在測試的請求的部分 –

+0

您是否可以嘗試將sendResponse調用中的值204更改爲200,並查看會發生什麼情況。 204代碼意味着沒有內容,並且瀏覽器不期望內容主體。這就是爲什麼沒有找到記錄就沒有加載的原因。參考:http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html – conor

回答

1

問題是,如果在數據庫中找不到適當的數據,您將返回HTTP 204,這告訴瀏覽器顯示的內容完全沒有。你的情況並非如此。

您仍想輸出找不到任何內容的消息。

要解決您的問題,需要用200替換代碼中的204這兩個實例。

我修改測試你的代碼使用:注意,什麼都不會顯示。要讓消息顯示在變量$status_header變量204200

<?php 
     $status_header = 'HTTP/1.1 204'; 

     // set the status 
     header($status_header); 
     // set the content type 
     header('Content-type: text/html'); 

     echo "Can you see me???"; 
?> 

注:當測試這個總是關閉選項卡,並使用一個新的選項卡每個呼叫,否則它看起來就像是從以前調用加載數據,像你解釋。