欢迎各位兄弟 发布技术文章
这里的技术是共享的
由ORTIX 发表于2年前
正如标题所示,我们如何处理这样的错误?
在我的具体情况下,uri中的slug不存在,我正在搜索数据库中的这个lug子。如果不存在,则会抛出此错误。我想要一个404错误出现。怎么处理这个?
public function getBySlug($slug)
{
// TODO: handle fail
$show = Show::where('slug', '=', $slug)->firstOrFail();
return $show;
}
我不知道,有几种方法,也许这个?
if ( ! $show)
{
App::abort(404);
}
该方法在没有找到与查询匹配的记录时firstOrFail()
抛出Illuminate\Database\Eloquent\ModelNotFoundException
。你可以在你的错误处理程序的一个捕获这个异常,在解释返回一个404响应文件。
//file app/start/global.php
App::error(function(Illuminate\Database\Eloquent\ModelNotFoundException $e){
return Response::make('Not found',404);
//or
//return Response::view('404-view',null,404);
});
我什么都不做 如果这样的话,恶意用户会试图访问非优质的东西。哎哟,他们错了就可以了。
@luanrodriguesp在App\Exceptions\Handler
http://laravel.com/docs/5.0/errors#handling-errors
PUBLISHED 2 YEARS AGO BY ORTIX
As the title says, how do we go about handling such an error?
In my specific case the slug in the uri doesn't exist and I'm searching the database for that slug. If it doesn't exist, this error is thrown. I want a 404 error to appear. How would one go about handling this?
public function getBySlug($slug)
{
// TODO: handle fail
$show = Show::where('slug', '=', $slug)->firstOrFail();
return $show;
}
I don't know, there's a few ways, maybe this?
if ( ! $show)
{
App::abort(404);
}
The method firstOrFail()
throws an Illuminate\Database\Eloquent\ModelNotFoundException
when it does not find a record matching the query. You can catch this exception in one of your error handlers to return a 404 response as explained in documentation.
//file app/start/global.php
App::error(function(Illuminate\Database\Eloquent\ModelNotFoundException $e){
return Response::make('Not found',404);
//or
//return Response::view('404-view',null,404);
});
I would do nothing. If something like this appends its that a malicious user try to access non exising stuffs. Whooops somethig went wrong is ok for them.
@usman in L5 where shuould i put the code?
thank you.
@luanrodriguesp In App\Exceptions\Handler
http://laravel.com/docs/5.0/errors#handling-errors