ExceptionRenderer.php 11 KB

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