我想为我的cakephp项目中的每个控制器创建异常。例子:
class UsersController extends AppController {
public function add(){
if(!$this->User->save($this->request->data)){
throw new UserException('Error save User/add');
}
}
}
class FriendsController extends AppController {
public function add(){
if(!$this->Friend->save($this->request->data)){
throw new FriendException('Error save Friend/add');
}
}
}
我正在尝试这个,但不工作…永远不要绘制登录类异常user/friend
在app/Config/core.phpConfigure::write('Exception.handler', 'UserException::handle');
Configure::write('Exception.handler', 'FriendException::handle');
在app/Config/bootstrap.php App::uses('UserException', 'Lib');
App::uses('FriendException', 'Lib');
在app/Lib/UserException.php class UserException {
public static function handle($error) {
$this->log($error)
}
}
在app/Lib/FriendException.php class FriendException {
public static function handle($error) {
$this->log($error)
}
}
任何想法?的问候!
每个控制器的例外似乎都是多余的。为什么你需要两个异常类UserException
和FriendException
,当他们是相同的,唯一的区别是你传递的消息?此外,日志记录功能是内置在核心的ExceptionHandler
。您可以只抛出CakeException
或RuntimeException
所需的消息。
你意识到你的代码了吗?
Configure::write('Exception.handler', 'UserException::handle');
Configure::write('Exception.handler', 'FriendException::handle');
正在覆盖配置相同的变量?
无论如何,'Exception.handler'
配置意味着指定处理所有异常的类。您可能会混淆异常类和错误处理程序类。异常类没有任何handle()
方法。您的异常类应该扩展CakeException
并覆盖所需的方法/属性。
使用CakeDC Utils插件,它带有一个可配置的EmailErrorHandler,可以根据错误级别发送电子邮件。