ExceptionRenderer.php 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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 MIT License (http://www.opensource.org/licenses/mit-license.php)
  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. try {
  141. $controller = new CakeErrorController($request, $response);
  142. $controller->startupProcess();
  143. } catch (Exception $e) {
  144. if (!empty($controller) && $controller->Components->enabled('RequestHandler')) {
  145. $controller->RequestHandler->startup($controller);
  146. }
  147. }
  148. if (empty($controller)) {
  149. $controller = new Controller($request, $response);
  150. $controller->viewPath = 'Errors';
  151. }
  152. return $controller;
  153. }
  154. /**
  155. * Renders the response for the exception.
  156. *
  157. * @return void
  158. */
  159. public function render() {
  160. if ($this->method) {
  161. call_user_func_array(array($this, $this->method), array($this->error));
  162. }
  163. }
  164. /**
  165. * Generic handler for the internal framework errors CakePHP can generate.
  166. *
  167. * @param CakeException $error
  168. * @return void
  169. */
  170. protected function _cakeError(CakeException $error) {
  171. $url = $this->controller->request->here();
  172. $code = ($error->getCode() >= 400 && $error->getCode() < 506) ? $error->getCode() : 500;
  173. $this->controller->response->statusCode($code);
  174. $this->controller->set(array(
  175. 'code' => $code,
  176. 'url' => h($url),
  177. 'name' => h($error->getMessage()),
  178. 'error' => $error,
  179. '_serialize' => array('code', 'url', 'name')
  180. ));
  181. $this->controller->set($error->getAttributes());
  182. $this->_outputMessage($this->template);
  183. }
  184. /**
  185. * Convenience method to display a 400 series page.
  186. *
  187. * @param Exception $error
  188. * @return void
  189. */
  190. public function error400($error) {
  191. $message = $error->getMessage();
  192. if (!Configure::read('debug') && $error instanceof CakeException) {
  193. $message = __d('cake', 'Not Found');
  194. }
  195. $url = $this->controller->request->here();
  196. $this->controller->response->statusCode($error->getCode());
  197. $this->controller->set(array(
  198. 'name' => h($message),
  199. 'url' => h($url),
  200. 'error' => $error,
  201. '_serialize' => array('name', 'url')
  202. ));
  203. $this->_outputMessage('error400');
  204. }
  205. /**
  206. * Convenience method to display a 500 page.
  207. *
  208. * @param Exception $error
  209. * @return void
  210. */
  211. public function error500($error) {
  212. $message = $error->getMessage();
  213. if (!Configure::read('debug')) {
  214. $message = __d('cake', 'An Internal Error Has Occurred.');
  215. }
  216. $url = $this->controller->request->here();
  217. $code = ($error->getCode() > 500 && $error->getCode() < 506) ? $error->getCode() : 500;
  218. $this->controller->response->statusCode($code);
  219. $this->controller->set(array(
  220. 'name' => h($message),
  221. 'message' => h($url),
  222. 'error' => $error,
  223. '_serialize' => array('name', 'message')
  224. ));
  225. $this->_outputMessage('error500');
  226. }
  227. /**
  228. * Convenience method to display a PDOException.
  229. *
  230. * @param PDOException $error
  231. * @return void
  232. */
  233. public function pdoError(PDOException $error) {
  234. $url = $this->controller->request->here();
  235. $code = 500;
  236. $this->controller->response->statusCode($code);
  237. $this->controller->set(array(
  238. 'code' => $code,
  239. 'url' => h($url),
  240. 'name' => h($error->getMessage()),
  241. 'error' => $error,
  242. '_serialize' => array('code', 'url', 'name', 'error')
  243. ));
  244. $this->_outputMessage($this->template);
  245. }
  246. /**
  247. * Generate the response using the controller object.
  248. *
  249. * @param string $template The template to render.
  250. * @return void
  251. */
  252. protected function _outputMessage($template) {
  253. try {
  254. $this->controller->render($template);
  255. $this->controller->afterFilter();
  256. $this->controller->response->send();
  257. } catch (MissingViewException $e) {
  258. $attributes = $e->getAttributes();
  259. if (isset($attributes['file']) && strpos($attributes['file'], 'error500') !== false) {
  260. $this->_outputMessageSafe('error500');
  261. } else {
  262. $this->_outputMessage('error500');
  263. }
  264. } catch (Exception $e) {
  265. $this->_outputMessageSafe('error500');
  266. }
  267. }
  268. /**
  269. * A safer way to render error messages, replaces all helpers, with basics
  270. * and doesn't call component methods.
  271. *
  272. * @param string $template The template to render
  273. * @return void
  274. */
  275. protected function _outputMessageSafe($template) {
  276. $this->controller->layoutPath = null;
  277. $this->controller->subDir = null;
  278. $this->controller->viewPath = 'Errors/';
  279. $this->controller->layout = 'error';
  280. $this->controller->helpers = array('Form', 'Html', 'Session');
  281. $view = new View($this->controller);
  282. $this->controller->response->body($view->render($template, 'error'));
  283. $this->controller->response->type('html');
  284. $this->controller->response->send();
  285. }
  286. }