我想做一些非常类似于
this的事情,但是在CakePHP世界中寻找AJAX请求.目前我这样做:
$this->autoRender = false; $this->response->statusCode(500);
它基于this.但是这个解决方案不允许我包含像Rails示例中的自定义消息,这样,在我的客户端错误处理程序中,我可以显示500错误响应中包含的消息.
我如何在CakePHP中实现与Ruby on Rails示例相同的功能?
你可以按照Cookbook:
http://book.cakephp.org/2.0/en/development/exceptions.html中的说明使用CakeExceptions但是如果你想使用自定义消息,我发现除了在生产模式下使用debug = 1之外别无他法:(
这是我使用内置方法的方法:
在你的控制器中:
if($this->request->is('ajax')){
Configure::write('debug',1);
}
if(!$allowed) {
throw new InternalErrorException('Keep your fingers away from me!'); // 500 error
}
在/app/View/Errors/error500.ctp中的AJAX调用中使用时,更改错误模板以输出除错误之外的任何内容:
<?PHP
if($this->request->is('ajax')):
// Output for AJAX calls
echo $name;
else:
//Standard CakePHP output ?>
<h2><?PHP echo $name; ?></h2>
<p class="error">
<strong><?PHP echo __d('cake','Error'); ?>: </strong>
<?PHP echo __d('cake','An Internal Error Has Occurred.'); ?>
</p>
<?PHP
if (Configure::read('debug') > 0 ):
echo $this->element('exception_stack_trace');
endif;
endif; ?>
然后,您可以解析AJAX中返回的文本.这是我使用的jQuery部分:
//...
error: function (request) {
yourErrorShowingFunction(_this,request.responseText);
}
//...
希望这可以帮助 :)
如果有人知道如何在生产模式下使用自定义错误(不覆盖调试模式),我会非常高兴!