4

In the following code in app/Exceptions/Handler.php, the first one doesn't work but the second one does.

dd(get_class($exception)); outputs "Illuminate\Database\Eloquent\ModelNotFoundException".

The first one is similar to the doc. How can I make it work using 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);
    }
shin
  • 31,901
  • 69
  • 184
  • 271
  • Try to add \ like this : `if ($exception instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) { //... }` and see if it will work ! – Maraboc Jul 05 '17 at 17:43
  • No it doesn't work either. – shin Jul 05 '17 at 18:25
  • 1
    try to add `use Illuminate\Database\Eloquent\ModelNotFoundException as ModelNotFoundException;` on top an then `if ($exception instanceof ModelNotFoundException) { //... }` – Maraboc Jul 05 '17 at 18:35
  • 1
    Yes, it worked. Can you put this in the answer so that I can tick it as a solution? Thanks. – shin Jul 06 '17 at 08:35

2 Answers2

6

To use instanceof you must use the full class name, and if your class has a namespace then you should use the fully qualified class name of the class.

And there is an other way to use instanceof using a short name (alias) for a given class thanks to use statement, in your case you can use it like so :

use Illuminate\Database\Eloquent\ModelNotFoundException as ModelNotFoundException; // on top of course :) 

if ($exception instanceof ModelNotFoundException) {
        return response()->json(['error'=>['message'=>'Resouce not found']], 404);
}
Maraboc
  • 10,550
  • 3
  • 37
  • 48
2

Sometimes an $exception is rethrown, so try to use

$exception->getPrevious() instanceof XXX

or

get_class($exception->getPrevious()) == 'XXX'
Luís Cruz
  • 14,780
  • 16
  • 68
  • 100
ALeX inSide
  • 484
  • 3
  • 10