Custom error handler for Laravel 4
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.
Leave a Reply