Skip to content

Exceptions in nested function calls are not handled #723

@kokoshneta

Description

@kokoshneta

When handling exceptions in callback routes, it seems the exception must be thrown directly in the route definition itself. If you call another function in the route definition, which then throws the exception, the exception is not handled by the exception handler, and instead an empty status-500 page is loaded.

Here is a minimal case to illustrate (assume the CustomExceptionHandler from the demo package is being used):

// helpers.php

function fileResponse($path) {
  if (!file_exists($path)) throw new NotFoundHttpException(code: 404);
  require_once $path;
}
// routes.php

require_once 'helpers.php';

Route::group(['exceptionHandler' => CustomExceptionHandler::class], function () {
  Route::get('/working/{id}', function ($id) {
    $path = "/path/to/files/{$id}.htm";
    if (!file_exists($path)) throw new NotFoundHttpException(code: 404);
    require_once $path;
  });
  
  Route::get('/not-working/{id}', function ($id) {
    $path = "/path/to/files/{$id}.htm";
    fileResponse($path);
  });
});

If you go to /working/5, you will get the contents of /path/to/files/5.htm if it exists; if it doesn’t, the exception handler catches the exception and renders whatever is in your DefaultController@notFound.

If you go to /not-working/5, you will still get the contents of /path/to/files/5.htm if it exists; but if it doesn’t, the exception handler is not invoked, and you get a 500 error with no content, which different agents will render differently (e.g., Safari just shows a blank page, while Firefox gives you a built-in “Looks like there’s a problem with this site” page). It appears the exception does not bubble up from the defined function to the calling closure, but I can’t identify anything in Router::handleException() or Router::routeRequest() that would cause this to be the case.

Am I missing something obvious here?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions