Laravel 4:创建默认路由

时间:2013-09-22 10:06:40

标签: php laravel laravel-4

我正在尝试在我的Laravel 4 REST API中创建一个默认路由,当我的其他任何定义的路由都没有匹配请求时,该路由会将特定错误返回给调用者。

这可能吗?不幸的是,我在文档中没有找到任何内容,所以我玩了一遍并尝试使用通配符(*)作为routes.php中的最后一个路径定义,但这不起作用。

Route::when("*", function(){
    throw new CustomizedException('Route not found...');
});

当我有这条路线并做artisan routes时,我得到一个例外: {"error":{"type":"ErrorException","message":"Object of class Closure could not be converted to string","file":"\/Applications\/MAMP\/htdocs\/CampaigningTools\/vendor\/laravel\/framework\/src\/Illuminate\/Foundation\/Console\/RoutesCommand.php","line":153}}

调用不存在的路由不会触发我自定义的异常,但标准的异常: {"error":{"type":"Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException","message":"","file":"\/Applications\/MAMP\/htdocs\/CampaigningTools\/vendor\/laravel\/framework\/src\/Illuminate\/Routing\/Router.php","line":1429}}

我也尝试使用any作为建议使用in this post,但这也不起作用:

Route::any( '(.*)', function( $page ){
    throw new ValidationException('Custom error');
});

当我呼叫一条不存在的路线时,这条路线也不会发射。

任何提示,我做错了什么都会受到赞赏。

4 个答案:

答案 0 :(得分:19)

我花了一些时间来弄清楚这一点,实际上@devo非常接近:

Route::get('{slug}', function($slug) {

    // check your DB for $slug, get the page, etc...

})->where('slug', '^.*');

这也会抓住/。如果您更愿意单独处理主页,请将正则表达式更改为:where(' slug',' ^。+');

答案 1 :(得分:8)

如果没有匹配的路由,Laravel会抛出“Symfony \ Component \ HttpKernel \ Exception \ NotFoundHttpException”。您可以简单地编写自己的错误处理程序来捕获该异常并执行其他操作(查看http://laravel.com/docs/errors)。

添加以下两个块之一(例如,在“应用程序错误处理程序”块中的“app / start / global.php”中):

App::error(function(\Symfony\Component\HttpKernel\Exception\NotFoundHttpException $exception, $code)
{
    // do something
});

或者:

App::missing(function($exception)
{
    // do something
});

答案 2 :(得分:1)

尝试这样的事情,

Route::get('{slug}', function($slug) {
    // get the page from database using Page model
    $page = Page::where('slug', '=', $slug)->first();

    if ( is_null($page) ) {
        return App::abort(404);
    }

    return View::make('page')->with('page',$page);
});

// Show 404 Page

App::missing(function($exception)
{
    return Response::view('errors.missing', array(), 404);
});

答案 3 :(得分:0)

尝试将其放在路径文件的末尾?

Route::any( '/{default?}', function( $page ){
    throw new ValidationException('Custom error');
});

或者

Route::any('/{default?}', 'TestController@yourMethod'); // pointing to a method displaying a 404 custom page