Custom error handler for Laravel 4

Custom error handler for Laravel 4

Custom error handler for Laravel

I build API service for a mobile application and I faced a problem with the error reporting with Laravel.

Laravel is awesome framework and is great for RESTful application or building API that’s why it’s my first choice.

But I had one problem, my API should produce only JSON and my application can consume only JSON. So HTML error pages are pointless and needless for me. I had a specific case where a PHP error was causing problems but I also wanted to handle all PHP and display them appropriately for my app. Here is the solution:

[cc lang=”php”]App::error(function(Exception $exception, $code)
{
if(Config::get(‘app.debug’)) {
Log::error($exception);
} else {
return Response::json(array(‘error’ => $exception->getMessage()), $code);
}
});[/cc]

There is an error handler in app/start/global.php which handles all exceptions including PHP errors of type ErrorException. You have no control in the code so even if you use try/catch block it will ignore it, have no idea why haven’t dug that deep, but you just can’t handle the PHP errors. With the custom handler in my case I just print the error message as JSON string so I can handle that in my mobile application.

It's only fair to share...Buffer this pageShare on Facebook0Tweet about this on TwitterShare on Google+0Share on LinkedIn0Share on Reddit0Pin on Pinterest0Email this to someone
About

Just a guy with strong interest in PHP and Web technologies

Posted in Laravel, PHP Tagged with: , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*