【问题标题】:Laravel error handling, get_class vs instanceofLaravel 错误处理,get_class 与 instanceof
【发布时间】:2017-12-09 05:09:17
【问题描述】:

在 app/Exceptions/Handler.php 中的以下代码中,第一个不起作用,但第二个起作用。

dd(get_class($exception)); 输出“Illuminate\Database\Eloquent\ModelNotFoundException”。

第一个是similar to the doc。如何使用instanceof 使其工作?

    public function render($request, Exception $exception)
    {
        //dd(get_class($exception));
        // this does not work.
        if ($exception instanceof Illuminate\Database\Eloquent\ModelNotFoundException
) {
            return response()->json(['error'=>['message'=>'Resouce not found']], 404);
        }
        // This one works.
        if(get_class($exception) == "Illuminate\Database\Eloquent\ModelNotFoundException") {
            return response()->json(['error'=>['message'=>'Resouce not found']], 404);
        }

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

【问题讨论】:

  • 尝试像这样添加 \ :if ($exception instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) { //... } 看看它是否会起作用!
  • 不,它也不起作用。
  • 尝试在顶部添加use Illuminate\Database\Eloquent\ModelNotFoundException as ModelNotFoundException; 然后if ($exception instanceof ModelNotFoundException) { //... }
  • 是的,它奏效了。您能否将其放入答案中,以便我将其作为解决方案打勾?谢谢。

标签: laravel-5.4 laravel-exceptions


【解决方案1】:

有时 $exception 会被重新抛出,因此请尝试使用

$exception->getPrevious() instanceof XXX

get_class($exception->getPrevious()) == 'XXX'

【讨论】:

    【解决方案2】:

    要使用instanceof,您必须使用完整的类名,如果您的类有命名空间,那么您应该使用类的完全限定类名。

    由于use 声明,还有另一种方法可以使用给定类的短名称(别名)使用instanceof,在您的情况下,您可以像这样使用它:

    use Illuminate\Database\Eloquent\ModelNotFoundException as ModelNotFoundException; // on top of course :) 
    
    if ($exception instanceof ModelNotFoundException) {
            return response()->json(['error'=>['message'=>'Resouce not found']], 404);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-07
      • 2015-03-09
      • 2013-12-08
      • 2018-07-02
      • 1970-01-01
      • 2018-05-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多