2016-11-28 124 views
0

1)我想拋出一個錯誤,當id沒有設置或ID是錯誤的。 2)我想拋出一個錯誤,當id被設置,但不在數據庫中。 爲什麼不給我什麼,當我把錯誤的ID?我期望顯示錯誤消息。cakephp NotFoundException不顯示任何東西

ItemController.php

<?php 
/** 
* Created by PhpStorm. 
* User: Marian39 
* Date: 11/17/2016 
* Time: 8:07 PM 
*/ 

namespace App\Controller; 

use Cake\Network\Exception\NotFoundException; 
use Cake\Datasource\Exception\RecordNotFoundException; 

class ItemsController extends AppController 
{ 
    public function view($id = null) 
    { 
     if(!$id) 
     { 
      throw new NotFoundException(__("id is not set or wrong")); 
     } 

     $data= $this->Items->findById($id); 

     $display = $this->Items->get($id); 



try { 
      $display= $this->Items->get($id); 
    } 
catch (RecordNotFoundException $e) { 
    //no code need 
      } 


     $this->set('items', $data); 

     $this->set('error', $display); 
    } 

    public function index() 
    { 
     $data = $this->Items->find('all', array('order'=>'year')); 
     $count = $this->Items->find()->count(); 
     $info = array('items'=>$data, 
         'count' => $count); 
     $this->set($info); 
     // $this->set('items', $data); 
     // $this->set('count', $count); 

     //this->set('color', 'blue'); 
    } 

} 
?> 

view.ctp從模板:

<?php foreach($items as $item): ?> 

<div> 
    <h2> 
     <?php echo h($item['title']);?> 
     <?php echo h($item['year']);?> 
    </h2> 
    <p> 
     Length: <?php echo h($item['length']);?> 
    </p> 
    <div> 
     <?php echo h($item['description']);?> 
    </div> 
</div> 

<?php endforeach; ?> 

回答

1

爲了增強異常處理,你應該使用get()代替findById()。

If the get operation does not find any results a Cake\Datasource\Exception\RecordNotFoundException will be raised.

You can either catch this exception yourself, or allow CakePHP to convert it into a 404 error.

爲了檢查它是否是一個有效的記錄,你需要提及此之上:

namespace App\Controller; 

use Cake\Network\Exception\NotFoundException; 
use Cake\Datasource\Exception\RecordNotFoundException; 

public function view($id = null) 
{ 
    /* Other code*/ 
    try { 
     $data= $this->Items->get($id); 
    } catch (RecordNotFoundException $e) { 
     // Show appropriate user-friendly message 
    } 
} 
+0

嗨!我把代碼放在課堂上面。錯誤:當不在對象上下文中時使用$ this? 應該做出什麼樣的更改更具體?我不明白太好..我是初學者。 –

+0

你應該放這一行:'use Cake \ Datasource \ Exception \ RecordNotFoundException; '在課程開始前。並把try catch塊放在你的'public function index()' –

+0

謝謝你的幫助!我修改了我的代碼,只有這樣。請告訴我,如果沒關係。 –