Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[Debug] enhanced error messages for uncaught exceptions #11034

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 3, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions src/Symfony/Bridge/Twig/Extension/CodeExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ class CodeExtension extends \Twig_Extension
public function __construct($fileLinkFormat, $rootDir, $charset)
{
$this->fileLinkFormat = empty($fileLinkFormat) ? ini_get('xdebug.file_link_format') : $fileLinkFormat;
$this->rootDir = str_replace('\\', '/', $rootDir).'/';
$this->rootDir = str_replace('\\', '/', dirname($rootDir)).'/';
$this->charset = $charset;
}

Expand Down Expand Up @@ -164,12 +164,14 @@ public function fileExcerpt($file, $line)
*/
public function formatFile($file, $line, $text = null)
{
$file = trim($file);

if (null === $text) {
$file = trim($file);
$text = $file;
$text = str_replace('\\', '/', $file);
if (0 === strpos($text, $this->rootDir)) {
$text = str_replace($this->rootDir, '', str_replace('\\', '/', $text));
$text = sprintf('<abbr title="%s">kernel.root_dir</abbr>/%s', $this->rootDir, $text);
$text = substr($text, strlen($this->rootDir));
$text = explode('/', $text, 2);
$text = sprintf('<abbr title="%s%2$s">%s</abbr>%s', $this->rootDir, $text[0], isset($text[1]) ? '/'.$text[1] : '');
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
&#187;&#160;<a href="{{ path('_profiler_export', { 'token': token }) }}">Export</a>
</div>
{% endif %}
&#187;&#160;<label for="file">Import</label><br>
<input type="file" name="file" id="file"><br>
&#187;&#160;<label for="file">Import</label><br />
<input type="file" name="file" id="file"><br />
<button type="submit" class="sf-button">
<span class="border-l">
<span class="border-r">
Expand Down
5 changes: 5 additions & 0 deletions src/Symfony/Component/Debug/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
CHANGELOG
=========

2.6.0
-----

* enhanced error messages for uncaught exceptions

2.5.0
-----

Expand Down
9 changes: 4 additions & 5 deletions src/Symfony/Component/Debug/ErrorHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ function ($row) {
$context = $c;
}

$exception = sprintf('%s: %s in %s line %d', isset($this->levels[$level]) ? $this->levels[$level] : $level, $message, $file, $line);
$exception = sprintf('%s: %s', isset($this->levels[$level]) ? $this->levels[$level] : $level, $message);
if ($context && class_exists('Symfony\Component\Debug\Exception\ContextErrorException')) {
// Checking for class existence is a work around for https://bugs.php.net/42098
$exception = new ContextErrorException($exception, 0, $level, $file, $line, $context);
Expand Down Expand Up @@ -317,12 +317,11 @@ private function handleFatalError($exceptionHandler, array $error)
set_error_handler('var_dump', 0);
ini_set('display_errors', 1);

$level = isset($this->levels[$error['type']]) ? $this->levels[$error['type']] : $error['type'];
$message = sprintf('%s: %s in %s line %d', $level, $error['message'], $error['file'], $error['line']);
$exception = sprintf('%s: %s', $this->levels[$error['type']], $error['message']);
if (0 === strpos($error['message'], 'Allowed memory') || 0 === strpos($error['message'], 'Out of memory')) {
$exception = new OutOfMemoryException($message, 0, $error['type'], $error['file'], $error['line'], 3, false);
$exception = new OutOfMemoryException($exception, 0, $error['type'], $error['file'], $error['line'], 3, false);
} else {
$exception = new FatalErrorException($message, 0, $error['type'], $error['file'], $error['line'], 3, true);
$exception = new FatalErrorException($exception, 0, $error['type'], $error['file'], $error['line'], 3, true);

foreach ($this->getFatalErrorHandlers() as $handler) {
if ($e = $handler->handleError($error, $exception)) {
Expand Down
39 changes: 24 additions & 15 deletions src/Symfony/Component/Debug/ExceptionHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -207,29 +207,24 @@ public function getContent(FlattenException $exception)
$total = $count + 1;
foreach ($exception->toArray() as $position => $e) {
$ind = $count - $position + 1;
$class = $this->abbrClass($e['class']);
$message = nl2br($e['message']);
$class = $this->formatClass($e['class']);
$message = nl2br(htmlspecialchars($e['message'], ENT_QUOTES | ENT_SUBSTITUTE, $this->charset));
$content .= sprintf(<<<EOF
<div class="block_exception clear_fix">
<h2><span>%d/%d</span> %s: %s</h2>
<h2><span>%d/%d</span> %s%s:<br />%s</h2>
</div>
<div class="block">
<ol class="traces list_exception">

EOF
, $ind, $total, $class, $message);
, $ind, $total, $class, $this->formatPath($e['trace'][0]['file'], $e['trace'][0]['line']), $message);
foreach ($e['trace'] as $trace) {
$content .= ' <li>';
if ($trace['function']) {
$content .= sprintf('at %s%s%s(%s)', $this->abbrClass($trace['class']), $trace['type'], $trace['function'], $this->formatArgs($trace['args']));
$content .= sprintf('at %s%s%s(%s)', $this->formatClass($trace['class']), $trace['type'], $trace['function'], $this->formatArgs($trace['args']));
}
if (isset($trace['file']) && isset($trace['line'])) {
if ($linkFormat = ini_get('xdebug.file_link_format')) {
$link = str_replace(array('%f', '%l'), array($trace['file'], $trace['line']), $linkFormat);
$content .= sprintf(' in <a href="%s" title="Go to source">%s line %s</a>', $link, $trace['file'], $trace['line']);
} else {
$content .= sprintf(' in %s line %s', $trace['file'], $trace['line']);
}
$content .= $this->formatPath($trace['file'], $trace['line']);
}
$content .= "</li>\n";
}
Expand Down Expand Up @@ -305,8 +300,8 @@ public function getStylesheet(FlattenException $exception)
overflow: hidden;
word-wrap: break-word;
}
.sf-reset li a { background:none; color:#868686; text-decoration:none; }
.sf-reset li a:hover { background:none; color:#313131; text-decoration:underline; }
.sf-reset a { background:none; color:#868686; text-decoration:none; }
.sf-reset a:hover { background:none; color:#313131; text-decoration:underline; }
.sf-reset ol { padding: 10px 0; }
.sf-reset h1 { background-color:#FFFFFF; padding: 15px 28px; margin-bottom: 20px;
-webkit-border-radius: 10px;
Expand Down Expand Up @@ -342,13 +337,27 @@ private function decorate($content, $css)
EOF;
}

private function abbrClass($class)
private function formatClass($class)
{
$parts = explode('\\', $class);

return sprintf("<abbr title=\"%s\">%s</abbr>", $class, array_pop($parts));
}

private function formatPath($path, $line)
{
$path = htmlspecialchars($path, ENT_QUOTES | ENT_SUBSTITUTE, $this->charset);
$file = preg_match('#[^/\\\\]*$#', $path, $file) ? $file[0] : $path;

if ($linkFormat = ini_get('xdebug.file_link_format')) {
$link = str_replace(array('%f', '%l'), array($path, $line), $linkFormat);

return sprintf(' <a href="%s" title="Go to source">in %s line %d</a>', $link, $file, $line);
}

return sprintf(' <a title="in %s line %3$d" ondblclick="var f=this.innerHTML;this.innerHTML=this.title;this.title=f;">in %s line %d</a>', $path, $file, $line);
}

/**
* Formats an array as a string.
*
Expand All @@ -361,7 +370,7 @@ private function formatArgs(array $args)
$result = array();
foreach ($args as $key => $item) {
if ('object' === $item[0]) {
$formattedValue = sprintf("<em>object</em>(%s)", $this->abbrClass($item[1]));
$formattedValue = sprintf("<em>object</em>(%s)", $this->formatClass($item[1]));
} elseif ('array' === $item[0]) {
$formattedValue = sprintf("<em>array</em>(%s)", is_array($item[1]) ? $this->formatArgs($item[1]) : $item[1]);
} elseif ('string' === $item[0]) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,29 +51,23 @@ public function handleError(array $error, FatalErrorException $exception)
if (false !== $namespaceSeparatorIndex = strrpos($fullyQualifiedClassName, '\\')) {
$className = substr($fullyQualifiedClassName, $namespaceSeparatorIndex + 1);
$namespacePrefix = substr($fullyQualifiedClassName, 0, $namespaceSeparatorIndex);
$message = sprintf(
'Attempted to load %s "%s" from namespace "%s" in %s line %d. Do you need to "use" it from another namespace?',
$typeName,
$className,
$namespacePrefix,
$error['file'],
$error['line']
);
$message = sprintf('Attempted to load %s "%s" from namespace "%s".', $typeName, $className, $namespacePrefix);
$tail = ' for another namespace?';
} else {
$className = $fullyQualifiedClassName;
$message = sprintf(
'Attempted to load %s "%s" from the global namespace in %s line %d. Did you forget a use statement for this %s?',
$typeName,
$className,
$error['file'],
$error['line'],
$typeName
);
$message = sprintf('Attempted to load %s "%s" from the global namespace.', $typeName, $className);
$tail = '?';
}

if ($classes = $this->getClassCandidates($className)) {
$message .= sprintf(' Perhaps you need to add a use statement for one of the following: %s.', implode(', ', $classes));
if ($candidates = $this->getClassCandidates($className)) {
$tail = array_pop($candidates).'"?';
if ($candidates) {
$tail = ' for e.g. "'.implode('", "', $candidates).'" or "'.$tail;
} else {
$tail = ' for "'.$tail;
}
}
$message .= ' Did you forget a "use" statement'.$tail;

return new ClassNotFoundException($message, $exception);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,21 +47,10 @@ public function handleError(array $error, FatalErrorException $exception)
if (false !== $namespaceSeparatorIndex = strrpos($fullyQualifiedFunctionName, '\\')) {
$functionName = substr($fullyQualifiedFunctionName, $namespaceSeparatorIndex + 1);
$namespacePrefix = substr($fullyQualifiedFunctionName, 0, $namespaceSeparatorIndex);
$message = sprintf(
'Attempted to call function "%s" from namespace "%s" in %s line %d.',
$functionName,
$namespacePrefix,
$error['file'],
$error['line']
);
$message = sprintf('Attempted to call function "%s" from namespace "%s".', $functionName, $namespacePrefix);
} else {
$functionName = $fullyQualifiedFunctionName;
$message = sprintf(
'Attempted to call function "%s" from the global namespace in %s line %d.',
$functionName,
$error['file'],
$error['line']
);
$message = sprintf('Attempted to call function "%s" from the global namespace.', $functionName);
}

$candidates = array();
Expand All @@ -81,9 +70,13 @@ public function handleError(array $error, FatalErrorException $exception)

if ($candidates) {
sort($candidates);
$message .= ' Did you mean to call: '.implode(', ', array_map(function ($val) {
return '"'.$val.'"';
}, $candidates)).'?';
$last = array_pop($candidates).'"?';
if ($candidates) {
$candidates = 'e.g. "'.implode('", "', $candidates).'" or "'.$last;
} else {
$candidates = '"'.$last;
}
$message .= ' Did you mean to call '.$candidates;
}

return new UndefinedFunctionException($message, $exception);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public function handleError(array $error, FatalErrorException $exception)
$className = $matches[1];
$methodName = $matches[2];

$message = sprintf('Attempted to call method "%s" on class "%s" in %s line %d.', $methodName, $className, $error['file'], $error['line']);
$message = sprintf('Attempted to call method "%s" on class "%s".', $methodName, $className);

$candidates = array();
foreach (get_class_methods($className) as $definedMethodName) {
Expand All @@ -46,7 +46,13 @@ public function handleError(array $error, FatalErrorException $exception)

if ($candidates) {
sort($candidates);
$message .= sprintf(' Did you mean to call: "%s"?', implode('", "', $candidates));
$last = array_pop($candidates).'"?';
if ($candidates) {
$candidates = 'e.g. "'.implode('", "', $candidates).'" or "'.$last;
} else {
$candidates = '"'.$last;
}
$message .= ' Did you mean to call '.$candidates;
}

return new UndefinedMethodException($message, $exception);
Expand Down
61 changes: 5 additions & 56 deletions src/Symfony/Component/Debug/Tests/ErrorHandlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,9 @@ public function testNotice()
$this->assertEquals('triggerNotice', $trace[1]['function']);
$this->assertEquals('::', $trace[1]['type']);

$this->assertEquals(__FILE__, $trace[1]['file']);
$this->assertEquals(__CLASS__, $trace[2]['class']);
$this->assertEquals('testNotice', $trace[2]['function']);
$this->assertEquals(__FUNCTION__, $trace[2]['function']);
$this->assertEquals('->', $trace[2]['type']);
} catch (\Exception $e) {
restore_error_handler();
Expand Down Expand Up @@ -123,10 +124,10 @@ public function testHandle()

$handler = ErrorHandler::register(3);
try {
$handler->handle(111, 'foo', 'foo.php', 12, array());
$handler->handle(4, 'foo', 'foo.php', 12, array());
} catch (\ErrorException $e) {
$this->assertSame('111: foo in foo.php line 12', $e->getMessage());
$this->assertSame(111, $e->getSeverity());
$this->assertSame('Parse Error: foo in foo.php line 12', $e->getMessage());
$this->assertSame(4, $e->getSeverity());
$this->assertSame('foo.php', $e->getFile());
$this->assertSame(12, $e->getLine());
}
Expand Down Expand Up @@ -193,56 +194,4 @@ public function testHandle()
throw $e;
}
}

/**
* @dataProvider provideFatalErrorHandlersData
*/
public function testFatalErrorHandlers($error, $class, $translatedMessage)
{
$handler = new ErrorHandler();
$exceptionHandler = new MockExceptionHandler();

$m = new \ReflectionMethod($handler, 'handleFatalError');
$m->setAccessible(true);
$m->invoke($handler, array($exceptionHandler, 'handle'), $error);

$this->assertInstanceof($class, $exceptionHandler->e);
// class names are case insensitive and PHP/HHVM do not return the same
$this->assertSame(strtolower($translatedMessage), strtolower($exceptionHandler->e->getMessage()));
$this->assertSame($error['type'], $exceptionHandler->e->getSeverity());
$this->assertSame($error['file'], $exceptionHandler->e->getFile());
$this->assertSame($error['line'], $exceptionHandler->e->getLine());
}

public function provideFatalErrorHandlersData()
{
return array(
// undefined function
array(
array(
'type' => 1,
'line' => 12,
'file' => 'foo.php',
'message' => 'Call to undefined function test_namespaced_function_again()',
),
'Symfony\Component\Debug\Exception\UndefinedFunctionException',
'Attempted to call function "test_namespaced_function_again" from the global namespace in foo.php line 12. Did you mean to call: "\\symfony\\component\\debug\\tests\\test_namespaced_function_again"?',
),
// class not found
array(
array(
'type' => 1,
'line' => 12,
'file' => 'foo.php',
'message' => 'Class \'WhizBangFactory\' not found',
),
'Symfony\Component\Debug\Exception\ClassNotFoundException',
'Attempted to load class "WhizBangFactory" from the global namespace in foo.php line 12. Did you forget a use statement for this class?',
),
);
}
}

function test_namespaced_function_again()
{
}
Original file line number Diff line number Diff line change
Expand Up @@ -160,8 +160,8 @@ public function testToArray(\Exception $exception, $statusCode)

$this->assertEquals(array(
array(
'message'=> 'test',
'class'=>'Exception',
'message' => 'test',
'class' => 'Exception',
'trace'=>array(array(
'namespace' => '', 'short_class' => '', 'class' => '','type' => '','function' => '', 'file' => 'foo.php', 'line' => 123,
'args' => array()
Expand Down
Loading