Laravel: resource not found exception

时间:2015-06-15 15:20:47

标签: laravel-5

Say you have a simple resource route like this:

Route::resource('overview', 'OverviewController');

And hit routes which you know don't exist. For example:

/overview/sdflkjdsflkjsd  
/overview/sdflkjdsflkjsd/edit

Which in my case throws Trying to get property of non-object error from my view (as no resource is found)

I looked into adding 'Regular Expression Parameter Constraints' from the docs, but it looks like these are not available for resource routes either (plus don't really fix the problem).

I'm looking for a way to throw a single exception for this kind of thing, which I can then handle once, rather than add logic to each action (or at least the show and edit actions).. if possible.

EDIT After looking around github, I found the exception in the Symphony repo here. Is there a way I can hook into it?

1 个答案:

答案 0 :(得分:2)

由于您收到Trying to get property of non-object错误,我认为您是通过YourModel::find();

获取资源的

我建议您改用YourModel::findOrFail()。然后,您将获得一种名为ModelNotFoundException的特定类型的异常。只需为此注册一个错误处理程序。

例如,

App::error(function(ModelNotFoundException $e)
{
    return Response::make('Not Found', 404);
});

UPDATE:这实际上会进入Laravel 5.1中app/Exceptions/Handler.php文件内的render()方法,当然代码会使用传递的$ e参数。

public function render($request, Exception $e)
{
   if ($e instanceof ModelNotFoundException)
   {
        return \Response::make('Not Found', 404);
   }
    return parent::render($request, $e);
}