I have an application written with the Laravel PHP framework. My main application listens to the 404 and 500 events.
Event::listen('404', function()
{
return Response::error('404');
});
Event::listen('500', function()
{
return Response::error('500');
});
This show my custom error pages to the user. But now, I’ve also built an API, which lives in a bundle called api. This API will be used via Ajax, so I want to handle errors differently. So I added these events to the routes.php of the api bundle:
Event::listen('404', function()
{
return Response::json(array('status' => 'error', 'message' => 'API endpoint not found.'));
});
Event::listen('500', function()
{
return Response::json(array('status' => 'error', 'message' => 'Internal server error'));
});
Unfortunately, this doesn’t work, it still displays the HTML error page. How can I respond differently to 404/500 errors depending on API or main application?
Thanks!
Have you tried overriding the main applications listeners from within your bundle? This should remove them as listeners when your bundle is called and leave only your bundles listeners for the events.
You can override events using the
Event::override()method instead of the listen method.