panthro
panthro

Reputation: 24061

Throwing errors in Laravel

In my package, before I perform a query on my database I check if some of the params provided are valid:

//check
if(!$this->checkId($id)) //error

//do the query
$user = User::find($id);

What's the best way to handle this in a laravel package?

Throw an error? If so, which kind? Do an app abort?

Upvotes: 1

Views: 2196

Answers (2)

user1669496
user1669496

Reputation: 33048

Using findOrFail()

There is a pretty good method that Laravel provides just for this case called findOrFail().

What you can do is use that and then catch the exception.

try {
    $user = User::findOrFail($queryParam);
} catch(ModelNotFoundException $e) {
    // Do things that should happen here if your query parameter does not exist.
}

If you do not wish to catch it here, you can setup a listener for this exception. You can place it anywhere you wish as long as it's being autoloaded.

use Illuminate\Database\Eloquent\ModelNotFoundException;

App::error(function(ModelNotFoundException $e)
{
    return Response::make('Not Found', 404);
});

Throwing an exception

If all you want to do is throw an error if a query param isn't available, you can throw any of the exceptions found here... https://github.com/symfony/symfony/tree/master/src/Symfony/Component/HttpKernel/Exception

If none suit you, you can create your own and just extend Symfony\Component\HttpKernel\Exception\HttpException and throw new YourCustomException($statusCode, $message);. Just follow what they've done in the other exception classes and it should be fairly easy.

Then you can modify the the "exception listener" to catch YourCustomException.

Here is a tutorial I found... http://fideloper.com/laravel4-error-handling

Upvotes: 1

c-griffin
c-griffin

Reputation: 3026

I would use Event Listeners for the most control.

Create an events.php in your app directory and include it in app/start/global.php Or, you can register anywhere in your package.

Create a listener:

Event::listen('paramCheck.noId', function($id)
{

    // do some logic, log something, return something, throw an error...

});

Then fire the event from whenever you need to:

if(!$this->checkId($id))
    $returnFromEvent = Event::fire('paramCheck.noId', array($id));

Upvotes: 0

Related Questions