feature #27499 Improved an error message related to controllers (javiereguiluz)

This PR was squashed before being merged into the 4.2-dev branch (closes #27499).

Discussion
----------

Improved an error message related to controllers

| Q             | A
| ------------- | ---
| Branch?       | master
| Bug fix?      | no
| New feature?  | yes
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets | -
| License       | MIT
| Doc PR        | -

This proposal is irrelevant for experienced users but it may be useful for newcomers. After having delivered several introductory Symfony training, I can say that when someone adds `return "some string...";` in their controller, the error message is confusing:

![before](https://user-images.githubusercontent.com/73419/40959468-0faf790a-689d-11e8-9ce1-f6e0caf4b113.png)

Maybe we can reword it a bit? (I'm open for suggestions to improve the error message)

![after](https://user-images.githubusercontent.com/73419/40959505-29747070-689d-11e8-834e-92bf18760469.png)

Commits
-------

7510c3a335 Improved an error message related to controllers
This commit is contained in:
Fabien Potencier 2018-06-27 11:26:40 +02:00
commit 0252a00311

View File

@ -157,7 +157,7 @@ class HttpKernel implements HttpKernelInterface, TerminableInterface
if ($event->hasResponse()) {
$response = $event->getResponse();
} else {
$msg = sprintf('The controller must return a response (%s given).', $this->varToString($response));
$msg = sprintf('The controller must return a "Symfony\Component\HttpFoundation\Response" object but it returned %s.', $this->varToString($response));
// the user may have forgotten to return something
if (null === $response) {
@ -253,20 +253,20 @@ class HttpKernel implements HttpKernelInterface, TerminableInterface
private function varToString($var): string
{
if (is_object($var)) {
return sprintf('Object(%s)', get_class($var));
return sprintf('an object of type %s', get_class($var));
}
if (is_array($var)) {
$a = array();
foreach ($var as $k => $v) {
$a[] = sprintf('%s => %s', $k, $this->varToString($v));
$a[] = sprintf('%s => ...', $k);
}
return sprintf('Array(%s)', implode(', ', $a));
return sprintf('an array ([%s])', mb_substr(implode(', ', $a), 0, 255));
}
if (is_resource($var)) {
return sprintf('Resource(%s)', get_resource_type($var));
return sprintf('a resource (%s)', get_resource_type($var));
}
if (null === $var) {
@ -274,11 +274,19 @@ class HttpKernel implements HttpKernelInterface, TerminableInterface
}
if (false === $var) {
return 'false';
return 'a boolean value (false)';
}
if (true === $var) {
return 'true';
return 'a boolean value (true)';
}
if (is_string($var)) {
return sprintf('a string ("%s%s")', mb_substr($var, 0, 255), mb_strlen($var) > 255 ? '...' : '');
}
if (is_numeric($var)) {
return sprintf('a number (%s)', (string) $var);
}
return (string) $var;