2013-09-22 77 views
1

我試圖在我的Laravel 4 REST API中創建一個默認路由,當我的其他定義的路由都不匹配請求時,返回一個特定的錯誤給調用者。Laravel 4:創建一個默認路由

這可能嗎?不幸的是,我沒有在文檔中找到任何內容,所以我四處遊玩並嘗試使用通配符(*)作爲我的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'); 
}); 

當我呼叫不存在的路線時,此路線也不會發射。

任何提示,我做錯了,將不勝感激。

回答

8

如果沒有匹配的路由,Laravel拋出一個 「的Symfony \分量\ HttpKernel \異常\ NotFoundHttpException」。您可以簡單地編寫自己的錯誤處理程序來捕獲該異常並執行其他操作(查看http://laravel.com/docs/errors)。

(在 「應用程序錯誤處理程序」 塊例如,在你的 「應用程序/啓動/ global.php」)添加下面的兩個塊之一:

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

或者:

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

非常感謝你 –

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

這僅適用於簡單URL像/ foo中。如果你有/富/酒吧它不會趕上它... – ivanhoe

19

我花了一段時間才能弄清楚這一點,其實@devo是非常接近:

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

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

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

這將趕上/過。如果您希望單獨處理主頁,請將正則表達式更改爲:where('slug','^。+');

+3

這是一個非常好的答案。需要更多upvotes。 –

+0

我打算寫相同的答案... +1以節省我的時間:D –

0

試着把這個放在路由文件的末尾?

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

或者

Route::any('/{default?}', '[email protected]'); // pointing to a method displaying a 404 custom page