2013-03-06 125 views
1

我嘗試使用AbstractRestfulController。我創建控制器類:如何處理錯誤(AbstractRestfulController)?

class MyController extends AbstractRestfulController{ 

    public function getList(){ 
     $data = array(); 

     return new JsonModel(array(
      'data' => $data, 
     )); 
    } 

    public function get($id){ 
     $data = array(); 

     return new JsonModel(array(
      'data' => $data, 
     )); 
    } 

    public function create($data){ 
     $data = array(); 

     return new JsonModel(array(
      'data' => $data, 
     )); 
    } 

    public function update($id, $data){ 
     $data = array(); 

     return new JsonModel(array(
      'data' => $data, 
     )); 
    } 

    public function delete($id){ 
     $data = array(); 

     return new JsonModel(array(
      'data' => $data, 
     )); 
    } 

} 

和路由:

return array(
    'router' => array(
     'routes' => array(
      'mylink' => array(
       'type' => 'Segment', 
       'options' => array(
        'route' => '/mylink[/:id]', 
        'constraints' => array(
         'id'  => '[0-9]+', 
        ), 
        'defaults' => array(
         'controller' => 'MyModule\Controller\My', 
        ), 
       ), 
      ), 
     ), 
    ), 
    'controllers' => array(
     'invokables' => array(
      'MyModule\Controller\My' => 'MyModule\Controller\MyController', 
     ), 
    ), 
    'view_manager' => array(
     'strategies' => array(
      'ViewJsonStrategy', 
     ), 
    ), 
); 

但是當用戶調用錯誤的方法或錯誤的ID或其他任何東西會發生什麼?我想親自處理。怎麼做?

回答

3

您的API仍然應該以請求的格式(json,xml等)返回響應,通常會使用一些錯誤代碼/消息來描述問題,以及相應的http響應代碼。您應該告訴消費者您的api預期的響應是什麼,但是當錯誤發生時應該由他們來處理。

從這個角度看它的設置的響應和填充相關信息返回模型的一個簡單的例子,一個典型的響應可能類似於以下...

public function get($id) 
{ 
    // some processing to find id ... 

    // no id found 
    if (!$found) { 
     // set 404 Not Found response 
     $this->getResponse()->setStatusCode(404); 
     // return message to client 
     return new JsonModel(array(
      'error' => 404, 
      'reason' => sprint_f('Requested id "%s" not found', $id'), 
     )); 
    } 
} 

顯然做同樣爲其他方法,並嘗試使用適當的HTTP response code

+0

但是,如果網址不正確?如果我在'template_map'中設置'error/404',它將返回標準文本/ html頁面的視圖/錯誤。我無法分配控制器/模塊/無論處理錯誤? – Nips 2013-03-06 10:25:25

+1

這不是你問的。對於一個不好的網址有更多的考慮,比如你的網站是否也提供標準的http頁面?如果沒有,你可以設計一個404視圖策略,在路由404響應的情況下返回一個JsonModel。如果它也處理http,則必須提出一個策略,可以確定這是一個錯誤的api請求還是誤輸入鏈接的真實用戶。我認爲你需要考慮什麼是可以接受的,就像我說的那樣,處理你的客戶錯誤不是你的責任。他們收到了404以及html而不是json響應應該就足夠了。 – Crisp 2013-03-06 10:41:35