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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:37:59  来源:igfitidea点击:

Laravel: Throw error from controller

phplaravel

提问by Feralheart

I have a project and if I want to access partner/XI got get property of non objecterror, 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.

在此处阅读更多相关信息。

回答by Matthew Daly

Use the abort()helper:

使用abort()助手:

abort(404);

There's also abort_if()and abort_unless()if you prefer. Whichever one you choose, you can pass it the required status code.

还有 abort_if()abort_unless(),如果你喜欢。无论您选择哪一个,您都可以将所需的状态代码传递给它。