Laravel:从控制器抛出错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46131745/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel: Throw error from controller
提问by Feralheart
I have a project and if I want to access partner/X
I got get property of non object
error, becouse I have less partners than X.
我有一个项目,如果我想访问partner/X
我会get property of non object
出错,因为我的合作伙伴比 X 少。
My question. How to tell the controller, that if the result of the modelquery is empty, than throw a 404 error
?
我的问题。如何告诉控制器,那if the result of the modelquery is empty, than throw a 404 error
?
My code is so far:
我的代码到目前为止:
public function showPartner($id = 0){
//Only allow numerical values
if ($id > 0){
$partner = Partner::find($id);
if (empty($partner)){
return ???
}
}
}
采纳答案by ishegg
Laravel has a specific method for that. If you use findOrFail($id)
, it will throw an Illuminate\Database\Eloquent\ModelNotFoundException
, so there's no need to throw an Exception by yourself.
Laravel 有一个特定的方法。如果您使用findOrFail($id)
,它将抛出一个Illuminate\Database\Eloquent\ModelNotFoundException
,因此您无需自己抛出异常。
If you mean "show the user an 404 error" instead of literally throwing an Exception, then catch it and abort()
:
如果您的意思是“向用户显示 404 错误”而不是从字面上抛出异常,则捕获它并abort()
:
public function showPartner($id = 0){
//Only allow numerical values
if ($id > 0){
try {
$partner = Partner::find($id);
// do your work
}
catch (Illuminate\Database\Eloquent\ModelNotFoundException $e) {
abort(404, "The Partner was not found");
}
}
}
Read more about this here.
在此处阅读更多相关信息。