如何在Laravel雄辩的模型中重写ModelNotFoundException?

如何在Laravel雄辩的模型中重写ModelNotFoundException?

问题描述:

我想知道是否有可能在某些条件/查询中找不到Laravel的Eloquent模型时抛出自定义异常?

I'm wondering, if it's possible, to throw custom exception, when on some condition/query Laravel's Eloquent model is not found?

例如,如果我有一个Page模型,如何抛出自定义的PageNotFound异常?

For example, if I have a Page model, how can I throw my custom, PageNotFound exception?

<?php 

namespace App;

use Illuminate\Database\Eloquent\Model;

class Page extends Model {
}

此模型将使用给定消息抛出ModelNotFoundException:

This model will throw ModelNotFoundException with the given message:

No query results for model [App\Page].

app/Exceptions/Handler.php中,尝试将以下代码添加到呈现函数的顶部

In app/Exceptions/Handler.php try adding the following code to the top of the render function

  public function render($request, Exception $e)
        {
            if ($e
                instanceof
                \Illuminate\Database\Eloquent\ModelNotFoundException) 
            {
              abort(404);
            }

            return parent::render($request, $e);
        }

编辑
一旦捕获到ModelNotFoundException对象,就可以对其调用 getModel() 以获取模型的类名.

EDIT
Once you catch the ModelNotFoundException object, you can call getModel() on it to get the classname of the model.