fractal5
fractal5

Reputation: 2132

Laravel Lumen - handle invalid route

In Lumen, how can I handle invalid routes (URLs)?

Lumen's documentation says to put abort(404); but I'm not where to put this.

If I put it in my route file, it gives me this error

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

This is the code where the error is thrown:

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
    }
}

This is the stuff in my route file (just added one route):

$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);
});

I suspect I'm not adding the abort command properly in the route file.

Ideally if the route isn't valid I want it to redirect to /ask URL.

Any help is appreciated. And please let me if any more info or code is needed. I'll add it to the question.

-----EDIT:-----

Without the abort() I get this error with an invalid URL:

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

This is line 1264 from the Application.php

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);
    }
}

As per the lumen documentation, this is the second way to handle an error which is what it seems to be doing.

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

But how can I show a 404 page instead of the error on the page?

Upvotes: 2

Views: 3705

Answers (1)

fractal5
fractal5

Reputation: 2132

I got this to work with the help of these links:

Mainly the first one. Bestmomo's answers did the trick. The second link is useful if you want to handle different kinds of errors 404, 500 etc.

I didn't have to add anything to my route file. Just had to change the app/Exceptions/Handler.php file as described in the answer. I will more detail here soon.

Make sure to add use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; in your Handler.php

Upvotes: 2

Related Questions