ExceptionRenderer.php 9.3 KB

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