【发布时间】:2013-12-26 19:04:03
【问题描述】:
我想指定是否在 url 地址中输入了除现有路由以外的任何内容(在 routes.php 中,然后显示 404 页面。
我知道这件事:
App::abort(404);
但是我怎样才能指定除了定义的路由之外的所有部分?
【问题讨论】:
我想指定是否在 url 地址中输入了除现有路由以外的任何内容(在 routes.php 中,然后显示 404 页面。
我知道这件事:
App::abort(404);
但是我怎样才能指定除了定义的路由之外的所有部分?
【问题讨论】:
您可以将其添加到您的 filters.php 文件中:
App::missing(function($exception)
{
return Response::view('errors.missing', array(), 404);
});
并创建errors.missing 视图文件以向他们显示错误。
编辑
如果您需要将数据传递给该视图,则第二个参数是您可以使用的数组:
App::missing(function($exception)
{
return Response::view('errors.missing', array('url' => Request::url()), 404);
});
【讨论】:
Laravel 5.2,而filters.php 不可用。你能建议我应该怎么做吗?
app/Http/Exceptions/Handler.php 文件,然后在 render() 方法中,添加这个检查:if ($e->getStatusCode() == 404) { return response()->view('errors.customView', ['data' => 'custom_data'], $e->getStatusCode()); }
我建议把它放到你的 app/start/global.php 中,因为这是 Laravel 默认处理它的地方(尽管 filters.php 也可以工作)。我通常使用这样的东西:
/*
|--------------------------------------------------------------------------
| Application Error Handler
|--------------------------------------------------------------------------
|
| Here you may handle any errors that occur in your application, including
| logging them or displaying custom views for specific errors. You may
| even register several error handlers to handle different types of
| exceptions. If nothing is returned, the default error view is
| shown, which includes a detailed stack trace during debug.
|
*/
App::error(function(Exception $exception, $code)
{
$pathInfo = Request::getPathInfo();
$message = $exception->getMessage() ?: 'Exception';
Log::error("$code - $message @ $pathInfo\r\n$exception");
if (Config::get('app.debug')) {
return;
}
switch ($code)
{
case 403:
return Response::view('errors/403', array(), 403);
case 500:
return Response::view('errors/500', array(), 500);
default:
return Response::view('errors/404', array(), $code);
}
});
然后只需在/views 中创建一个errors 文件夹并将错误页面内容放在那里。正如 Antonio 所说,您可以在 array() 中传递数据。
我从https://github.com/andrewelkins/Laravel-4-Bootstrap-Starter-Site借用了这个方法
【讨论】:
Laravel 5.2 和app/start/global.php。你能建议我应该怎么做吗?
对于使用 Laravel 5 的人来说,views 目录中有一个 errors 文件夹。您只需要在那里创建一个 404.blade.php 文件,当没有为 url 指定路由时,它将呈现此视图
【讨论】:
这是我仅用于使用模板布局显示错误 404 的方法。只需将以下代码添加到/app/start/global.php 文件中
App::missing(function($exception)
{
$layout = \View::make('layouts.error');
$layout->content = \View::make('views.errors.404');
return Response::make($layout, 404);
});
【讨论】: