4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Debug;
14 use Symfony\Component\HttpFoundation\Response;
15 use Symfony\Component\Debug\Exception\FlattenException;
16 use Symfony\Component\Debug\Exception\OutOfMemoryException;
19 * ExceptionHandler converts an exception to a Response object.
21 * It is mostly useful in debug mode to replace the default PHP/XDebug
22 * output with something prettier and more useful.
24 * As this class is mainly used during Kernel boot, where nothing is yet
25 * available, the Response content is always HTML.
27 * @author Fabien Potencier <fabien@symfony.com>
28 * @author Nicolas Grekas <p@tchwork.com>
30 class ExceptionHandler
35 private $caughtBuffer;
36 private $caughtLength;
37 private $fileLinkFormat;
39 public function __construct($debug = true, $charset = null, $fileLinkFormat = null)
41 if (false !== strpos($charset, '%')) {
42 @trigger_error('Providing $fileLinkFormat as second argument to '.__METHOD__.' is deprecated since version 2.8 and will be unsupported in 3.0. Please provide it as third argument, after $charset.', E_USER_DEPRECATED);
44 // Swap $charset and $fileLinkFormat for BC reasons
45 $pivot = $fileLinkFormat;
46 $fileLinkFormat = $charset;
49 $this->debug = $debug;
50 $this->charset = $charset ?: ini_get('default_charset') ?: 'UTF-8';
51 $this->fileLinkFormat = $fileLinkFormat ?: ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format');
55 * Registers the exception handler.
57 * @param bool $debug Enable/disable debug mode, where the stack trace is displayed
58 * @param string|null $charset The charset used by exception messages
59 * @param string|null $fileLinkFormat The IDE link template
63 public static function register($debug = true, $charset = null, $fileLinkFormat = null)
65 $handler = new static($debug, $charset, $fileLinkFormat);
67 $prev = set_exception_handler(array($handler, 'handle'));
68 if (is_array($prev) && $prev[0] instanceof ErrorHandler) {
69 restore_exception_handler();
70 $prev[0]->setExceptionHandler(array($handler, 'handle'));
77 * Sets a user exception handler.
79 * @param callable $handler An handler that will be called on Exception
81 * @return callable|null The previous exception handler if any
83 public function setHandler($handler)
85 if (null !== $handler && !is_callable($handler)) {
86 throw new \LogicException('The exception handler must be a valid PHP callable.');
88 $old = $this->handler;
89 $this->handler = $handler;
95 * Sets the format for links to source files.
97 * @param string $format The format for links to source files
99 * @return string The previous file link format
101 public function setFileLinkFormat($format)
103 $old = $this->fileLinkFormat;
104 $this->fileLinkFormat = $format;
110 * Sends a response for the given Exception.
112 * To be as fail-safe as possible, the exception is first handled
113 * by our simple exception handler, then by the user exception handler.
114 * The latter takes precedence and any output from the former is cancelled,
115 * if and only if nothing bad happens in this handling path.
117 public function handle(\Exception $exception)
119 if (null === $this->handler || $exception instanceof OutOfMemoryException) {
120 $this->failSafeHandle($exception);
125 $caughtLength = $this->caughtLength = 0;
127 ob_start(array($this, 'catchOutput'));
128 $this->failSafeHandle($exception);
129 while (null === $this->caughtBuffer && ob_end_flush()) {
130 // Empty loop, everything is in the condition
132 if (isset($this->caughtBuffer[0])) {
133 ob_start(array($this, 'cleanOutput'));
134 echo $this->caughtBuffer;
135 $caughtLength = ob_get_length();
137 $this->caughtBuffer = null;
140 call_user_func($this->handler, $exception);
141 $this->caughtLength = $caughtLength;
142 } catch (\Exception $e) {
143 if (!$caughtLength) {
144 // All handlers failed. Let PHP handle that now.
151 * Sends a response for the given Exception.
153 * If you have the Symfony HttpFoundation component installed,
154 * this method will use it to create and send the response. If not,
155 * it will fallback to plain PHP functions.
157 * @param \Exception $exception An \Exception instance
159 private function failSafeHandle(\Exception $exception)
161 if (class_exists('Symfony\Component\HttpFoundation\Response', false)
162 && __CLASS__ !== get_class($this)
163 && ($reflector = new \ReflectionMethod($this, 'createResponse'))
164 && __CLASS__ !== $reflector->class
166 $response = $this->createResponse($exception);
167 $response->sendHeaders();
168 $response->sendContent();
169 @trigger_error(sprintf("The %s::createResponse method is deprecated since 2.8 and won't be called anymore when handling an exception in 3.0.", $reflector->class), E_USER_DEPRECATED);
174 $this->sendPhpResponse($exception);
178 * Sends the error associated with the given Exception as a plain PHP response.
180 * This method uses plain PHP functions like header() and echo to output
183 * @param \Exception|FlattenException $exception An \Exception or FlattenException instance
185 public function sendPhpResponse($exception)
187 if (!$exception instanceof FlattenException) {
188 $exception = FlattenException::create($exception);
191 if (!headers_sent()) {
192 header(sprintf('HTTP/1.0 %s', $exception->getStatusCode()));
193 foreach ($exception->getHeaders() as $name => $value) {
194 header($name.': '.$value, false);
196 header('Content-Type: text/html; charset='.$this->charset);
199 echo $this->decorate($this->getContent($exception), $this->getStylesheet($exception));
203 * Creates the error Response associated with the given Exception.
205 * @param \Exception|FlattenException $exception An \Exception or FlattenException instance
207 * @return Response A Response instance
209 * @deprecated since 2.8, to be removed in 3.0.
211 public function createResponse($exception)
213 @trigger_error('The '.__METHOD__.' method is deprecated since version 2.8 and will be removed in 3.0.', E_USER_DEPRECATED);
215 if (!$exception instanceof FlattenException) {
216 $exception = FlattenException::create($exception);
219 return Response::create($this->getHtml($exception), $exception->getStatusCode(), $exception->getHeaders())->setCharset($this->charset);
223 * Gets the full HTML content associated with the given exception.
225 * @param \Exception|FlattenException $exception An \Exception or FlattenException instance
227 * @return string The HTML content as a string
229 public function getHtml($exception)
231 if (!$exception instanceof FlattenException) {
232 $exception = FlattenException::create($exception);
235 return $this->decorate($this->getContent($exception), $this->getStylesheet($exception));
239 * Gets the HTML content associated with the given exception.
241 * @param FlattenException $exception A FlattenException instance
243 * @return string The content as a string
245 public function getContent(FlattenException $exception)
247 switch ($exception->getStatusCode()) {
249 $title = 'Sorry, the page you are looking for could not be found.';
252 $title = 'Whoops, looks like something went wrong.';
258 $count = count($exception->getAllPrevious());
260 foreach ($exception->toArray() as $position => $e) {
261 $ind = $count - $position + 1;
262 $class = $this->formatClass($e['class']);
263 $message = nl2br($this->escapeHtml($e['message']));
264 $content .= sprintf(<<<'EOF'
265 <h2 class="block_exception clear_fix">
266 <span class="exception_counter">%d/%d</span>
267 <span class="exception_title">%s%s:</span>
268 <span class="exception_message">%s</span>
271 <ol class="traces list_exception">
274 , $ind, $total, $class, $this->formatPath($e['trace'][0]['file'], $e['trace'][0]['line']), $message);
275 foreach ($e['trace'] as $trace) {
277 if ($trace['function']) {
278 $content .= sprintf('at %s%s%s(%s)', $this->formatClass($trace['class']), $trace['type'], $trace['function'], $this->formatArgs($trace['args']));
280 if (isset($trace['file']) && isset($trace['line'])) {
281 $content .= $this->formatPath($trace['file'], $trace['line']);
283 $content .= "</li>\n";
286 $content .= " </ol>\n</div>\n";
288 } catch (\Exception $e) {
289 // something nasty happened and we cannot throw an exception anymore
291 $title = sprintf('Exception thrown when handling an exception (%s: %s)', get_class($e), $this->escapeHtml($e->getMessage()));
293 $title = 'Whoops, looks like something went wrong.';
299 <div id="sf-resetcontent" class="sf-reset">
307 * Gets the stylesheet associated with the given exception.
309 * @param FlattenException $exception A FlattenException instance
311 * @return string The stylesheet as a string
313 public function getStylesheet(FlattenException $exception)
316 .sf-reset { font: 11px Verdana, Arial, sans-serif; color: #333 }
317 .sf-reset .clear { clear:both; height:0; font-size:0; line-height:0; }
318 .sf-reset .clear_fix:after { display:block; height:0; clear:both; visibility:hidden; }
319 .sf-reset .clear_fix { display:inline-block; }
320 .sf-reset * html .clear_fix { height:1%; }
321 .sf-reset .clear_fix { display:block; }
322 .sf-reset, .sf-reset .block { margin: auto }
323 .sf-reset abbr { border-bottom: 1px dotted #000; cursor: help; }
324 .sf-reset p { font-size:14px; line-height:20px; color:#868686; padding-bottom:20px }
325 .sf-reset strong { font-weight:bold; }
326 .sf-reset a { color:#6c6159; cursor: default; }
327 .sf-reset a img { border:none; }
328 .sf-reset a:hover { text-decoration:underline; }
329 .sf-reset em { font-style:italic; }
330 .sf-reset h1, .sf-reset h2 { font: 20px Georgia, "Times New Roman", Times, serif }
331 .sf-reset .exception_counter { background-color: #fff; color: #333; padding: 6px; float: left; margin-right: 10px; float: left; display: block; }
332 .sf-reset .exception_title { margin-left: 3em; margin-bottom: 0.7em; display: block; }
333 .sf-reset .exception_message { margin-left: 3em; display: block; }
334 .sf-reset .traces li { font-size:12px; padding: 2px 4px; list-style-type:decimal; margin-left:20px; }
335 .sf-reset .block { background-color:#FFFFFF; padding:10px 28px; margin-bottom:20px;
336 -webkit-border-bottom-right-radius: 16px;
337 -webkit-border-bottom-left-radius: 16px;
338 -moz-border-radius-bottomright: 16px;
339 -moz-border-radius-bottomleft: 16px;
340 border-bottom-right-radius: 16px;
341 border-bottom-left-radius: 16px;
342 border-bottom:1px solid #ccc;
343 border-right:1px solid #ccc;
344 border-left:1px solid #ccc;
345 word-wrap: break-word;
347 .sf-reset .block_exception { background-color:#ddd; color: #333; padding:20px;
348 -webkit-border-top-left-radius: 16px;
349 -webkit-border-top-right-radius: 16px;
350 -moz-border-radius-topleft: 16px;
351 -moz-border-radius-topright: 16px;
352 border-top-left-radius: 16px;
353 border-top-right-radius: 16px;
354 border-top:1px solid #ccc;
355 border-right:1px solid #ccc;
356 border-left:1px solid #ccc;
358 word-wrap: break-word;
360 .sf-reset a { background:none; color:#868686; text-decoration:none; }
361 .sf-reset a:hover { background:none; color:#313131; text-decoration:underline; }
362 .sf-reset ol { padding: 10px 0; }
363 .sf-reset h1 { background-color:#FFFFFF; padding: 15px 28px; margin-bottom: 20px;
364 -webkit-border-radius: 10px;
365 -moz-border-radius: 10px;
367 border: 1px solid #ccc;
372 private function decorate($content, $css)
378 <meta charset="{$this->charset}" />
379 <meta name="robots" content="noindex,nofollow" />
381 /* Copyright (c) 2010, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.com/yui/license.html */
382 html{color:#000;background:#FFF;}body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,textarea,p,blockquote,th,td{margin:0;padding:0;}table{border-collapse:collapse;border-spacing:0;}fieldset,img{border:0;}address,caption,cite,code,dfn,em,strong,th,var{font-style:normal;font-weight:normal;}li{list-style:none;}caption,th{text-align:left;}h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal;}q:before,q:after{content:'';}abbr,acronym{border:0;font-variant:normal;}sup{vertical-align:text-top;}sub{vertical-align:text-bottom;}input,textarea,select{font-family:inherit;font-size:inherit;font-weight:inherit;}input,textarea,select{*font-size:100%;}legend{color:#000;}
384 html { background: #eee; padding: 10px }
386 #sf-resetcontent { width:970px; margin:0 auto; }
397 private function formatClass($class)
399 $parts = explode('\\', $class);
401 return sprintf('<abbr title="%s">%s</abbr>', $class, array_pop($parts));
404 private function formatPath($path, $line)
406 $path = $this->escapeHtml($path);
407 $file = preg_match('#[^/\\\\]*$#', $path, $file) ? $file[0] : $path;
409 if ($linkFormat = $this->fileLinkFormat) {
410 $link = strtr($this->escapeHtml($linkFormat), array('%f' => $path, '%l' => (int) $line));
412 return sprintf(' in <a href="%s" title="Go to source">%s line %d</a>', $link, $file, $line);
415 return sprintf(' in <a title="%s line %3$d" ondblclick="var f=this.innerHTML;this.innerHTML=this.title;this.title=f;">%s line %d</a>', $path, $file, $line);
419 * Formats an array as a string.
421 * @param array $args The argument array
425 private function formatArgs(array $args)
428 foreach ($args as $key => $item) {
429 if ('object' === $item[0]) {
430 $formattedValue = sprintf('<em>object</em>(%s)', $this->formatClass($item[1]));
431 } elseif ('array' === $item[0]) {
432 $formattedValue = sprintf('<em>array</em>(%s)', is_array($item[1]) ? $this->formatArgs($item[1]) : $item[1]);
433 } elseif ('string' === $item[0]) {
434 $formattedValue = sprintf("'%s'", $this->escapeHtml($item[1]));
435 } elseif ('null' === $item[0]) {
436 $formattedValue = '<em>null</em>';
437 } elseif ('boolean' === $item[0]) {
438 $formattedValue = '<em>'.strtolower(var_export($item[1], true)).'</em>';
439 } elseif ('resource' === $item[0]) {
440 $formattedValue = '<em>resource</em>';
442 $formattedValue = str_replace("\n", '', var_export($this->escapeHtml((string) $item[1]), true));
445 $result[] = is_int($key) ? $formattedValue : sprintf("'%s' => %s", $key, $formattedValue);
448 return implode(', ', $result);
452 * Returns an UTF-8 and HTML encoded string.
454 * @deprecated since version 2.7, to be removed in 3.0.
456 protected static function utf8Htmlize($str)
458 @trigger_error('The '.__METHOD__.' method is deprecated since version 2.7 and will be removed in 3.0.', E_USER_DEPRECATED);
460 return htmlspecialchars($str, ENT_QUOTES | (\PHP_VERSION_ID >= 50400 ? ENT_SUBSTITUTE : 0), 'UTF-8');
464 * HTML-encodes a string.
466 private function escapeHtml($str)
468 return htmlspecialchars($str, ENT_QUOTES | (\PHP_VERSION_ID >= 50400 ? ENT_SUBSTITUTE : 0), $this->charset);
474 public function catchOutput($buffer)
476 $this->caughtBuffer = $buffer;
484 public function cleanOutput($buffer)
486 if ($this->caughtLength) {
487 // use substr_replace() instead of substr() for mbstring overloading resistance
488 $cleanBuffer = substr_replace($buffer, '', 0, $this->caughtLength);
489 if (isset($cleanBuffer[0])) {
490 $buffer = $cleanBuffer;