user3489744
user3489744

Reputation:

Laravel ModelNotFound exception handling with namesapces

I have this problem where laravel ModelNotFound exeption handler catches all exceptions not only releated to eloquent.

I have added to global.php this code:

// this is default code
App::error(function(Exception $exception, $code)
{
    Log::error($exception);
});
// added code
App::error(function(ModelNotFoundException $exception)
{
    //do something, in my case redirect to 404 or whaterver
});

Controller has this partial code:

namespace CompanyName\Admin;

class PromosController extends CompanyNameAdminController {

    public function show($id) {
        $promo = Promo::findOrFail($id);
    }
}

Now if I try to pass id that dont exist I will recieve white page, code in app error does not execute. Other problem is that this App:error catches all Exeptions, like not found conrollers etc, basicly every exeption.

What I am doing wrong? I got this idea from Laracasts Exeptions handling episode, but somehow Im missing something. Because I get no feedback form Laravel about problem I am stuck. I suspect that namespaces has something to do with it but I am not sure..

EDIT: At last I found some feedback in console: 500 Internal Server Error HTML: Reload the page to get source for: http://cms.dev/admin/promos/533

Upvotes: 0

Views: 305

Answers (2)

mikro
mikro

Reputation: 125

ModelNotFoundException is not in that namespace, so it is not being found. Specify the qualified name:

App::error(function(Illuminate\Database\Eloquent\ModelNotFoundException $exception)
{
    //do something, in my case redirect to 404 or whaterver
});

Upvotes: 1

RMcLeod
RMcLeod

Reputation: 2581

The problem lies in the order of your Exception handlers. You have the handler for Exception first, as ModelNotFoundException extends Exception it gets handled by the Exception handler before it get's to the ModelNotFoundException. Simply switch them around and you should find it works as expected.

Upvotes: 0

Related Questions