Laravel Lumen - 处理无效路由

Laravel Lumen - handle invalid route

在 Lumen 中,如何处理无效路由(URLs)?

Lumen 的 documentation 说要放 abort(404); 但我不知道放在哪里。

如果我把它放在我的路由文件中,它会给我这个错误

Fatal error: Call to a member function send() on string in C:\....\vendor\laravel\lumen-framework\src\Application.php on line 408

这是抛出错误的代码:

protected function handleUncaughtException($e)
{
    $handler = $this->make('Illuminate\Contracts\Debug\ExceptionHandler');

    if ($e instanceof Error) {
        $e = new FatalThrowableError($e);
    }

    $handler->report($e);

    if ($this->runningInConsole()) {
        $handler->renderForConsole(new ConsoleOutput, $e);
    } else {
        $handler->render($this->make('request'), $e)->send(); <---line 408
    }
}

这是我的路由文件中的内容(只添加了一条路由):

$app->group(['middleware' => 'stratus_auth', 'namespace' => 'App\Http\Controllers'], function ($app) {

     $app->get('/login', ['as' => 'login', 'middleware' => 'user_logged', 'uses' => 'LoginController@index']);
     ...
     ...
     ...
     $app->abort(404);
});

我怀疑我没有在路由文件中正确添加中止命令。

理想情况下,如果路由无效,我希望它重定向到 /ask URL.

感谢任何帮助。如果需要更多信息或代码,请告诉我。我会把它添加到问题中。

-----编辑:-----

在没有 abort() 的情况下,我得到了一个无效的错误 URL:

exception 'Symfony\Component\HttpKernel\Exception\NotFoundHttpException' in C:\Empire\LifeLearn\Repos\lifelearn_sofie_application\vendor\laravel\lumen-framework\src\Application.php:1264

这是来自 Application.php

的第 1264 行
protected function handleDispatcherResponse($routeInfo)
{
    switch ($routeInfo[0]) {
        case Dispatcher::NOT_FOUND:
            throw new NotFoundHttpException;    <---ln 1264

        case Dispatcher::METHOD_NOT_ALLOWED:
            throw new MethodNotAllowedHttpException($routeInfo[1]);

        case Dispatcher::FOUND:
            return $this->handleFoundRoute($routeInfo);
    }
}

根据 lumen 文档,这是处理错误的第二种方法,它似乎正在这样做。

Secondly, you may manually throw an instance of Symfony\Component\HttpKernel\Exception\NotFoundHttpException.

但是如何显示 404 页面而不是页面上的错误?

我在这些 link 的帮助下使它工作:

主要是第一个。 Bestmomo 的回答起到了作用。如果你想处理不同类型的错误 404、500 等,第二个 link 很有用

我不需要在我的路线文件中添加任何东西。 只需按照答案中的描述更改 app/Exceptions/Handler.php 文件。我很快会在这里详细介绍。

确保在 Handler.php

中添加 use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;