Mohammad Ahmad
Mohammad Ahmad

Reputation: 745

Laravel handling exception

I'm just jump into laravel, this is my first project with.

Now i'm trying to add new exception to handler stack, but for sorry it's not working and i don't know why.

here is my exception class

namespace Lib\Modules\Users\Exceptions;

use Lib\Abstracts\AbstractException;

class ConnotCreateUserException extends AbstractException {

}

Here is my abstract

namespace Lib\Abstracts;

class AbstractException extends \Exception {

}

and here is my error registration inside app/start/global.php

App::error(function(Exception $exception, $code)
{
    Log::error($exception);
});

App::error(function(Lib\Modules\Users\Exceptions\ConnotCreateUserException $exception){
   return 'Sorry! Something is wrong with this account!';
});

when i throw the exception, i got blank page. but i'm sure it's handled as type of "\Exception" exception.

Thanks in advance

Upvotes: 0

Views: 1765

Answers (1)

Antonio Carlos Ribeiro
Antonio Carlos Ribeiro

Reputation: 87719

As the code looked fine, I just did some tests with it and it works for me, just make sure your namespaces are being loaded correctly by doing:

composer dump-autoload

But, anyway, here's what I did:

1) Created a PSR-4 autoloading for it:

"autoload": {
    "classmap": [
        ...
    ],
    "psr-4": {
        "Lib\\" : "app/App/Lib"
    }
},

2) Create the files using your very content:

app/App/Lib/Abstracts/AbstractException.php
app/App/Lib/Modules/Users/Exceptions/ConnotCreateUserException.php

3) executed

composer dump-autoload

4) opened vendor/composer/autoload_psr4.php just to make sure it was there:

return array(
    'Lib\\' => array($baseDir . '/app/App/Lib'),
);

5) Added this all in my routes.php file:

App::error(function(Exception $exception, $code)
{
    Log::error($exception);
});

App::error(function(Lib\Modules\Users\Exceptions\ConnotCreateUserException $exception){
   return 'Sorry! Something is wrong with this account!';
});

Route::get('/', function()
{
    throw new Lib\Modules\Users\Exceptions\ConnotCreateUserException("We should not get this message!", 1);
});

6) Hit:

http://server.dev/

And got the message

Sorry! Something is wrong with this account!

Upvotes: 1

Related Questions