当我使用ajax请求(我的情况下是jquery mobile)时,我也遇到了自定义异常和错误代码。这是我提出的解决方案,不涉及覆盖调试模式。它会在开发模式中引发自定义错误,并且还可以选择在生产模式下。我希望它可以帮助别人:
AppExceptionRenderer.php:
<?php
App::uses('ExceptionRenderer', 'Error');
class AppExceptionRenderer extends ExceptionRenderer
{
public function test($error)
{
$this->_sendAjaxError($error);
}
private function _sendAjaxError($error)
{
//only allow ajax requests and only send response if debug is on
if ($this->controller->request->is('ajax') && Configure::read('debug') > 0)
{
$this->controller->response->statusCode(500);
$response['errorCode'] = $error->getCode();
$response['errorMessage'] = $error->getMessage();
$this->controller->set(compact('response'));
$this->controller->layout = false;
$this->_outputMessage('errorjson');
}
}
}
你可以离开了Configure::read('debug') > 0
,如果你想显示在调试模式下除外。查看errorjson.ctp位于'Error/errorjson。CTP“:
<?php
echo json_encode($response);
?>
在这种情况下我的异常被称为
TestException
,并定义如下:
<?php
class TestException extends CakeException {
protected $_messageTemplate = 'Seems that %s is missing.';
public function __construct($message = null, $code = 2) {
if (empty($message)) {
$message = 'My custom exception.';
}
parent::__construct($message, $code);
}
}
如果我有一个自定义错误代码2,$code = 2
,为我的JSON响应。 Ajax响应将铸就一个错误500以下JSON数据:
{"errorCode":"2","errorMessage":"My custom exception."}
很明显,你还需要从您的控制器抛出异常:
throw new TestException();
,包括异常渲染http://book.cakephp.org/2.0/en/development/exceptions.html#using-a-custom-renderer-with-exception-renderer-to-handle-application-exceptions
这可能有点超出范围,但要处理我使用的JQuery中的ajax错误响应:
$(document).ajaxError(function (event, jqXHR, ajaxSettings, thrownError) {
//deal with my json error
});
即使这并不是我希望的答案,因为它调用了调试模式,我将其标记为正确,因为没有人似乎对此有任何想法。感谢您的努力! – 2012-08-22 17:15:12