ExceptionRenderer.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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\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. /**
  50. * Controller instance.
  51. *
  52. * @var Controller
  53. */
  54. public $controller = null;
  55. /**
  56. * Template to render for Cake\Core\Exception\Exception
  57. *
  58. * @var string
  59. */
  60. public $template = '';
  61. /**
  62. * The method corresponding to the Exception this object is for.
  63. *
  64. * @var string
  65. */
  66. public $method = '';
  67. /**
  68. * The exception being handled.
  69. *
  70. * @var \Exception
  71. */
  72. public $error = null;
  73. /**
  74. * Creates the controller to perform rendering on the error response.
  75. * If the error is a Cake\Core\Exception\Exception it will be converted to either a 400 or a 500
  76. * code error depending on the code used to construct the error.
  77. *
  78. * @param \Exception $exception Exception
  79. */
  80. public function __construct(Exception $exception)
  81. {
  82. $this->error = $exception;
  83. $this->controller = $this->_getController();
  84. }
  85. /**
  86. * Get the controller instance to handle the exception.
  87. * Override this method in subclasses to customize the controller used.
  88. * This method returns the built in `ErrorController` normally, or if an error is repeated
  89. * a bare controller will be used.
  90. *
  91. * @return \Cake\Controller\Controller
  92. * @triggers Controller.startup $controller
  93. */
  94. protected function _getController()
  95. {
  96. if (!$request = Router::getRequest(true)) {
  97. $request = Request::createFromGlobals();
  98. }
  99. $response = new Response();
  100. try {
  101. $class = App::className('Error', 'Controller', 'Controller');
  102. $controller = new $class($request, $response);
  103. $controller->startupProcess();
  104. $startup = true;
  105. } catch (Exception $e) {
  106. $startup = false;
  107. }
  108. // Retry RequestHandler, as another aspect of startupProcess()
  109. // could have failed. Ignore any exceptions out of startup, as
  110. // there could be userland input data parsers.
  111. if ($startup === false && !empty($controller) && isset($controller->RequestHandler)) {
  112. try {
  113. $event = new Event('Controller.startup', $controller);
  114. $controller->RequestHandler->startup($event);
  115. } catch (Exception $e) {
  116. }
  117. }
  118. if (empty($controller)) {
  119. $controller = new Controller($request, $response);
  120. $controller->viewPath = 'Error';
  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. $this->controller->set([
  148. 'message' => $message,
  149. 'url' => h($url),
  150. 'error' => $exception,
  151. 'code' => $code,
  152. '_serialize' => ['message', 'url', 'code']
  153. ]);
  154. if ($exception instanceof CakeException && $isDebug) {
  155. $this->controller->set($this->error->getAttributes());
  156. }
  157. return $this->_outputMessage($template);
  158. }
  159. /**
  160. * Render a custom error method/template.
  161. *
  162. * @param string $method The method name to invoke.
  163. * @param \Exception $exception The exception to render.
  164. * @return \Cake\Network\Response The response to send.
  165. */
  166. protected function _customMethod($method, $exception)
  167. {
  168. $result = call_user_func([$this, $method], $exception);
  169. $this->_shutdown();
  170. if (is_string($result)) {
  171. $this->controller->response->body($result);
  172. $result = $this->controller->response;
  173. }
  174. return $result;
  175. }
  176. /**
  177. * Get method name
  178. *
  179. * @param \Exception $exception Exception instance.
  180. * @return string
  181. */
  182. protected function _method(\Exception $exception)
  183. {
  184. list(, $baseClass) = namespaceSplit(get_class($exception));
  185. if(substr($baseClass, -9) === 'Exception') {
  186. $baseClass = substr($baseClass, 0, -9);
  187. }
  188. $method = Inflector::variable($baseClass) ?: 'error500';
  189. return $this->method = $method;
  190. }
  191. /**
  192. * Get error message.
  193. *
  194. * @param \Exception $exception Exception
  195. * @param int $code Error code
  196. * @return string Error message
  197. */
  198. protected function _message(\Exception $exception, $code)
  199. {
  200. $message = $this->error->getMessage();
  201. if (!Configure::read('debug') &&
  202. !($exception instanceof HttpException)
  203. ) {
  204. if ($code < 500) {
  205. $message = __d('cake', 'Not Found');
  206. } else {
  207. $message = __d('cake', 'An Internal Error Has Occurred.');
  208. }
  209. }
  210. return $message;
  211. }
  212. /**
  213. * Get template for rendering exception info.
  214. *
  215. * @param \Exception $exception Exception instance.
  216. * @param string $method Method name
  217. * @param int $code Error code
  218. * @return string Template name
  219. */
  220. protected function _template(\Exception $exception, $method, $code)
  221. {
  222. $isHttpException = $exception instanceof HttpException;
  223. if (!Configure::read('debug') && !$isHttpException) {
  224. $template = 'error500';
  225. if ($code < 500) {
  226. $template = 'error400';
  227. }
  228. return $this->template = $template;
  229. }
  230. if ($isHttpException) {
  231. $template = 'error500';
  232. if ($code < 500) {
  233. $template = 'error400';
  234. }
  235. return $this->template = $template;
  236. }
  237. $template = $method ?: 'error500';
  238. if ($exception instanceof \PDOException) {
  239. $template = 'pdo_error';
  240. }
  241. return $this->template = $template;
  242. }
  243. /**
  244. * Get an error code value within range 400 to 506
  245. *
  246. * @param \Exception $exception Exception
  247. * @return int Error code value within range 400 to 506
  248. */
  249. protected function _code(\Exception $exception)
  250. {
  251. $code = 500;
  252. $errorCode = $exception->getCode();
  253. if ($errorCode >= 400 && $errorCode < 506) {
  254. $code = $errorCode;
  255. }
  256. return $code;
  257. }
  258. /**
  259. * Generate the response using the controller object.
  260. *
  261. * @param string $template The template to render.
  262. * @return \Cake\Network\Response A response object that can be sent.
  263. */
  264. protected function _outputMessage($template)
  265. {
  266. try {
  267. $this->controller->render($template);
  268. return $this->_shutdown();
  269. } catch (MissingTemplateException $e) {
  270. $attributes = $e->getAttributes();
  271. if (isset($attributes['file']) && strpos($attributes['file'], 'error500') !== false) {
  272. return $this->_outputMessageSafe('error500');
  273. }
  274. return $this->_outputMessage('error500');
  275. } catch (MissingPluginException $e) {
  276. $attributes = $e->getAttributes();
  277. if (isset($attributes['plugin']) && $attributes['plugin'] === $this->controller->plugin) {
  278. $this->controller->plugin = null;
  279. }
  280. return $this->_outputMessageSafe('error500');
  281. } catch (\Exception $e) {
  282. return $this->_outputMessageSafe('error500');
  283. }
  284. }
  285. /**
  286. * A safer way to render error messages, replaces all helpers, with basics
  287. * and doesn't call component methods.
  288. *
  289. * @param string $template The template to render
  290. * @return \Cake\Network\Response A response object that can be sent.
  291. */
  292. protected function _outputMessageSafe($template)
  293. {
  294. $this->controller->layoutPath = null;
  295. $this->controller->subDir = null;
  296. $this->controller->viewPath = 'Error';
  297. $this->controller->layout = 'error';
  298. $this->controller->helpers = ['Form', 'Html', 'Session'];
  299. $view = $this->controller->createView();
  300. $this->controller->response->body($view->render($template, 'error'));
  301. $this->controller->response->type('html');
  302. return $this->controller->response;
  303. }
  304. /**
  305. * Run the shutdown events.
  306. *
  307. * Triggers the afterFilter and afterDispatch events.
  308. *
  309. * @return \Cake\Network\Response The response to serve.
  310. */
  311. protected function _shutdown()
  312. {
  313. $this->controller->dispatchEvent('Controller.shutdown');
  314. $dispatcher = DispatcherFactory::create();
  315. $args = [
  316. 'request' => $this->controller->request,
  317. 'response' => $this->controller->response
  318. ];
  319. $result = $dispatcher->dispatchEvent('Dispatcher.afterDispatch', $args);
  320. return $result->data['response'];
  321. }
  322. }