Skip to content

Instantly share code, notes, and snippets.

@simkimsia
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simkimsia/9107797 to your computer and use it in GitHub Desktop.
Save simkimsia/9107797 to your computer and use it in GitHub Desktop.
<?php
App::uses('AppException', 'Lib/Exception');
App::uses('ErrorHandler', 'Error');
class AppErrorHandler extends ErrorHandler {
public static function handleException(Exception $exception) {
if ($exception instanceof AppException) {
$element = 'default';
$message = $exception->getMessage();
$params = array('class' => 'error');
CakeSession::write('Message.flash', compact('message', 'element', 'params'));
if ($exception->hasRoute()) {
$controller = self::_getController($exception);
return $controller->redirect($exception->getRoute());
}
}
return parent::handleException($exception);
}
/**
* Get the controller instance to handle the exception.
* Override this method in subclasses to customize the controller used.
* This method returns the built in `CakeErrorController` normally, or if an error is repeated
* a bare controller will be used.
*
* @param Exception $exception The exception to get a controller for.
* @return Controller
*/
protected static function _getController($exception) {
App::uses('CakeErrorController', 'Controller');
if (!$request = Router::getRequest(true)) {
$request = new CakeRequest();
}
$response = new CakeResponse(array('charset' => Configure::read('App.encoding')));
try {
if (class_exists('AppController')) {
$controller = new CakeErrorController($request, $response);
}
} catch (Exception $e) {
}
if (empty($controller)) {
$controller = new Controller($request, $response);
$controller->viewPath = 'Errors';
}
return $controller;
}
}
?>
<?php
// app /Lib/Exception/AppException.php
class AppException extends CakeException {
public function __construct($message, $code = 0) {
parent::__construct($message, $code);
return $this;
}
public function getRoute() {
return $this->_attributes['route'];
}
public function setRoute($route = null) {
$this->_attributes['route'] = $route;
return $this;
}
public function hasRoute() {
return isset($this->_attributes['route']);
}
}
?>
<?php
// app /Lib/Exception/AppException.php
class AppException extends CakeException {
public function setRoute($route = null) {
$this->_attributes['route'] = $route;
}
public function getRoute() {
return $this->_attributes['route'];
}
public function hasRoute() {
return isset($this->_attributes['route']);
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment