Laravel对404的所有例外

the question is simple. Using laravel 5.6

I have for example, this route

Route::get('/services/{id}/{service}', ['as'=> 'services.show', 'uses' => 'ServicesController@show']);

where inside controller I do some fancy logic.

the question is: is there any other elegant way to throw a 404 when something fails inside the controller rather than the typical ErrorException page from laravel? (this is not the 404).

An easy example could be the id is not inserted in the database, so that is making the app fails, not returning a 404.

I guess one solution should be insert a try catch condition and if it fails render(404).. more or less..

Go to app/Exceptions If there is render method change it, or add the method.

Ex:

public function render($request, Exception $exception)
{
    if($exception instanceof NotFoundHttpException){
        return response()->view('errors/404', ['invalid_url'=>true], 404);
    }

    if ($exception instanceof TokenMismatchException && Auth::guest()) {
        error_log('Error :' . $exception->getMessage());
        abort(500);
    }

    if ($exception instanceof TokenMismatchException && getenv('APP_ENV') != 'local') {
        return redirect()->back()->withInput();
    }

    if($exception instanceof \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException && getenv('APP_ENV') != 'local') {
        error_log('Error :' . $exception->getMessage());
        abort(404);
    }

    if(($exception instanceof PDOException || $exception instanceof QueryException) && getenv('APP_ENV') != 'local') {
        error_log('Error :' . $exception->getMessage());
        abort(500);
    }

    if ($exception instanceof ClientException) {
        error_log('Error :' . $exception->getMessage());
        abort(500);
    }

    return parent::render($request, $exception);
}

You can try this

try{
 ... your fancy code here
}catch(Exception $e){
 abort(404, 'Custom 404 error message');
}

There is the elegant way to do what you want. Laravel has file called Handler.php inside your App/Exceptions directory. This file contains class called Handler and there is render method. That's it! You should make this method to transform all exceptions into 404 exception, something like this:

/**
 * @param $request
 * @param Exception $exception

 * @return mixed
 */
public function render($request, Exception $exception)
{
    // you could do abort(404) if you prefer helpers
    $notFoundException = new NotFoundHttpException($exception->getMessage());

    return parent::render($request, $notFoundException);
}