Slim errors - returns 500 on PHP syntax errors

My config error setting is:

displayErrorDetails => true,

Take this code:

$app->get('/', function(Request $request, Response $response) {
  $viewData = [];

  echo 'home page';

Works fine.

Now, if I create a code error like hinting equest instead of Request:

$app->get('/', function(equest $request, Response $response) {

I get the expected Slim error, thus:

But if I create any syntax error like forgetting a $, thus:

  viewData = [];

I get a 500 like this:

Same happens with every such syntax error like forgetting a semi-colon or a closing bracket.

Is this correct?

Edit: Using Nginx.

Hi! There is a typo in equest. Use Request and try it again.

You’ve misread my question. I created that typo on purpose to demonstrate a correct error response from Slim.

As opposed to the 500 error I receive for simple PHP syntax errors. I’m asking if that second error response is correct. I expect to see a PHP error from Slim.

If the file with the syntax error is not in the same PHP file, I get the desired result:

require 'script.php';

But if the syntax error is within the routes.php file then it’s impossible for PHP to catch this kind of error.
You may use the PHP linter php -l filename.php to check all files for syntax errors.

If I include an error form another file as you’ve done, I get a standard PHP error:

Parse error : syntax error, unexpected ‘echo’ (T_ECHO) in /sites/app/test.php** on line 13

I don’t get a Slim error output.

Why can’t PHP find errors in the routes.php file?

Slim will catch all Exceptions and “Throwable” (PHP errors) for you within the route callback.

$app->get('/', function (Request $request, Response $response, array $args) {
    // Slim can can handle parser errors here, but not outside the callback
    // Message: syntax error, unexpected '='
    require 'invalid.php';

    return $response;

But if you have a parsing error outside the routing callbacks, Slim doesn’t handle parsing errors.
This means, everything that PHP can handle is getting handled, but the syntax error must be “within” the “scope” of Slim and not “outside” of Slim. That’s why this invalid code will not be handled by Slim.

$app->get('/', function (Request $request, Response $response, array $args) {
    return $response;

// Not "handled" by Slim. You will get a native ParserError.
require 'invalid.php';


So I need to have two sets of error handlers: one for Slim and the PHP errors Slim is able to catch, and one for other PHP errors not handled by Slim.

Yes, indeed. But again, it is better to prevent syntax errors by using an IDE and the PHP linter and/or phpstan.

1 Like