cakephp NotFoundException不显示任何东西
问题描述:
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; ?>
答
为了增强异常处理,你应该使用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
}
}
嗨!我把代码放在课堂上面。错误:当不在对象上下文中时使用$ this? 应该做出什么样的更改更具体?我不明白太好..我是初学者。 –
你应该放这一行:'use Cake \ Datasource \ Exception \ RecordNotFoundException; '在课程开始前。并把try catch块放在你的'public function index()' –
谢谢你的帮助!我修改了我的代码,只有这样。请告诉我,如果没关系。 –