ExceptionRenderer.php 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. <?php
  2. /**
  3. * Exception Renderer
  4. *
  5. * Provides Exception rendering features. Which allow exceptions to be rendered
  6. * as HTML pages.
  7. *
  8. * PHP 5
  9. *
  10. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  11. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  12. *
  13. * Licensed under The MIT License
  14. * For full copyright and license information, please see the LICENSE.txt
  15. * Redistributions of files must retain the above copyright notice.
  16. *
  17. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  18. * @link http://cakephp.org CakePHP(tm) Project
  19. * @package Cake.Error
  20. * @since CakePHP(tm) v 2.0
  21. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  22. */
  23. App::uses('Sanitize', 'Utility');
  24. App::uses('Router', 'Routing');
  25. App::uses('CakeResponse', 'Network');
  26. App::uses('Controller', 'Controller');
  27. /**
  28. * Exception Renderer.
  29. *
  30. * Captures and handles all unhandled exceptions. Displays helpful framework errors when debug > 1.
  31. * When debug < 1 a CakeException will render 404 or 500 errors. If an uncaught exception is thrown
  32. * and it is a type that ExceptionHandler does not know about it will be treated as a 500 error.
  33. *
  34. * ### Implementing application specific exception rendering
  35. *
  36. * You can implement application specific exception handling in one of a few ways:
  37. *
  38. * - Create a AppController::appError();
  39. * - Create a subclass of ExceptionRenderer and configure it to be the `Exception.renderer`
  40. *
  41. * #### Using AppController::appError();
  42. *
  43. * This controller method is called instead of the default exception handling. It receives the
  44. * thrown exception as its only argument. You should implement your error handling in that method.
  45. *
  46. * #### Using a subclass of ExceptionRenderer
  47. *
  48. * Using a subclass of ExceptionRenderer gives you full control over how Exceptions are rendered, you
  49. * can configure your class in your core.php, with `Configure::write('Exception.renderer', 'MyClass');`
  50. * You should place any custom exception renderers in `app/Lib/Error`.
  51. *
  52. * @package Cake.Error
  53. */
  54. class ExceptionRenderer {
  55. /**
  56. * Controller instance.
  57. *
  58. * @var Controller
  59. */
  60. public $controller = null;
  61. /**
  62. * template to render for CakeException
  63. *
  64. * @var string
  65. */
  66. public $template = '';
  67. /**
  68. * The method corresponding to the Exception this object is for.
  69. *
  70. * @var string
  71. */
  72. public $method = '';
  73. /**
  74. * The exception being handled.
  75. *
  76. * @var Exception
  77. */
  78. public $error = null;
  79. /**
  80. * Creates the controller to perform rendering on the error response.
  81. * If the error is a CakeException it will be converted to either a 400 or a 500
  82. * code error depending on the code used to construct the error.
  83. *
  84. * @param Exception $exception Exception
  85. * @return mixed Return void or value returned by controller's `appError()` function
  86. */
  87. public function __construct(Exception $exception) {
  88. $this->controller = $this->_getController($exception);
  89. if (method_exists($this->controller, 'apperror')) {
  90. return $this->controller->appError($exception);
  91. }
  92. $method = $template = Inflector::variable(str_replace('Exception', '', get_class($exception)));
  93. $code = $exception->getCode();
  94. $methodExists = method_exists($this, $method);
  95. if ($exception instanceof CakeException && !$methodExists) {
  96. $method = '_cakeError';
  97. if (empty($template) || $template === 'internalError') {
  98. $template = 'error500';
  99. }
  100. } elseif ($exception instanceof PDOException) {
  101. $method = 'pdoError';
  102. $template = 'pdo_error';
  103. $code = 500;
  104. } elseif (!$methodExists) {
  105. $method = 'error500';
  106. if ($code >= 400 && $code < 500) {
  107. $method = 'error400';
  108. }
  109. }
  110. $isNotDebug = !Configure::read('debug');
  111. if ($isNotDebug && $method === '_cakeError') {
  112. $method = 'error400';
  113. }
  114. if ($isNotDebug && $code == 500) {
  115. $method = 'error500';
  116. }
  117. $this->template = $template;
  118. $this->method = $method;
  119. $this->error = $exception;
  120. }
  121. /**
  122. * Get the controller instance to handle the exception.
  123. * Override this method in subclasses to customize the controller used.
  124. * This method returns the built in `CakeErrorController` normally, or if an error is repeated
  125. * a bare controller will be used.
  126. *
  127. * @param Exception $exception The exception to get a controller for.
  128. * @return Controller
  129. */
  130. protected function _getController($exception) {
  131. App::uses('AppController', 'Controller');
  132. App::uses('CakeErrorController', 'Controller');
  133. if (!$request = Router::getRequest(true)) {
  134. $request = new CakeRequest();
  135. }
  136. $response = new CakeResponse();
  137. if (method_exists($exception, 'responseHeader')) {
  138. $response->header($exception->responseHeader());
  139. }
  140. if (class_exists('AppController')) {
  141. try {
  142. $controller = new CakeErrorController($request, $response);
  143. $controller->startupProcess();
  144. } catch (Exception $e) {
  145. if (!empty($controller) && $controller->Components->enabled('RequestHandler')) {
  146. $controller->RequestHandler->startup($controller);
  147. }
  148. }
  149. }
  150. if (empty($controller)) {
  151. $controller = new Controller($request, $response);
  152. $controller->viewPath = 'Errors';
  153. }
  154. return $controller;
  155. }
  156. /**
  157. * Renders the response for the exception.
  158. *
  159. * @return void
  160. */
  161. public function render() {
  162. if ($this->method) {
  163. call_user_func_array(array($this, $this->method), array($this->error));
  164. }
  165. }
  166. /**
  167. * Generic handler for the internal framework errors CakePHP can generate.
  168. *
  169. * @param CakeException $error
  170. * @return void
  171. */
  172. protected function _cakeError(CakeException $error) {
  173. $url = $this->controller->request->here();
  174. $code = ($error->getCode() >= 400 && $error->getCode() < 506) ? $error->getCode() : 500;
  175. $this->controller->response->statusCode($code);
  176. $this->controller->set(array(
  177. 'code' => $code,
  178. 'url' => h($url),
  179. 'name' => h($error->getMessage()),
  180. 'error' => $error,
  181. '_serialize' => array('code', 'url', 'name')
  182. ));
  183. $this->controller->set($error->getAttributes());
  184. $this->_outputMessage($this->template);
  185. }
  186. /**
  187. * Convenience method to display a 400 series page.
  188. *
  189. * @param Exception $error
  190. * @return void
  191. */
  192. public function error400($error) {
  193. $message = $error->getMessage();
  194. if (!Configure::read('debug') && $error instanceof CakeException) {
  195. $message = __d('cake', 'Not Found');
  196. }
  197. $url = $this->controller->request->here();
  198. $this->controller->response->statusCode($error->getCode());
  199. $this->controller->set(array(
  200. 'name' => h($message),
  201. 'url' => h($url),
  202. 'error' => $error,
  203. '_serialize' => array('name', 'url')
  204. ));
  205. $this->_outputMessage('error400');
  206. }
  207. /**
  208. * Convenience method to display a 500 page.
  209. *
  210. * @param Exception $error
  211. * @return void
  212. */
  213. public function error500($error) {
  214. $message = $error->getMessage();
  215. if (!Configure::read('debug')) {
  216. $message = __d('cake', 'An Internal Error Has Occurred.');
  217. }
  218. $url = $this->controller->request->here();
  219. $code = ($error->getCode() > 500 && $error->getCode() < 506) ? $error->getCode() : 500;
  220. $this->controller->response->statusCode($code);
  221. $this->controller->set(array(
  222. 'name' => h($message),
  223. 'message' => h($url),
  224. 'error' => $error,
  225. '_serialize' => array('name', 'message')
  226. ));
  227. $this->_outputMessage('error500');
  228. }
  229. /**
  230. * Convenience method to display a PDOException.
  231. *
  232. * @param PDOException $error
  233. * @return void
  234. */
  235. public function pdoError(PDOException $error) {
  236. $url = $this->controller->request->here();
  237. $code = 500;
  238. $this->controller->response->statusCode($code);
  239. $this->controller->set(array(
  240. 'code' => $code,
  241. 'url' => h($url),
  242. 'name' => h($error->getMessage()),
  243. 'error' => $error,
  244. '_serialize' => array('code', 'url', 'name', 'error')
  245. ));
  246. $this->_outputMessage($this->template);
  247. }
  248. /**
  249. * Generate the response using the controller object.
  250. *
  251. * @param string $template The template to render.
  252. * @return void
  253. */
  254. protected function _outputMessage($template) {
  255. try {
  256. $this->controller->render($template);
  257. $this->controller->afterFilter();
  258. $this->controller->response->send();
  259. } catch (MissingViewException $e) {
  260. $attributes = $e->getAttributes();
  261. if (isset($attributes['file']) && strpos($attributes['file'], 'error500') !== false) {
  262. $this->_outputMessageSafe('error500');
  263. } else {
  264. $this->_outputMessage('error500');
  265. }
  266. } catch (Exception $e) {
  267. $this->_outputMessageSafe('error500');
  268. }
  269. }
  270. /**
  271. * A safer way to render error messages, replaces all helpers, with basics
  272. * and doesn't call component methods.
  273. *
  274. * @param string $template The template to render
  275. * @return void
  276. */
  277. protected function _outputMessageSafe($template) {
  278. $this->controller->layoutPath = null;
  279. $this->controller->subDir = null;
  280. $this->controller->viewPath = 'Errors/';
  281. $this->controller->layout = 'error';
  282. $this->controller->helpers = array('Form', 'Html', 'Session');
  283. $view = new View($this->controller);
  284. $this->controller->response->body($view->render($template, 'error'));
  285. $this->controller->response->type('html');
  286. $this->controller->response->send();
  287. }
  288. }