php - How would you handle different error responses for different routes using Laravel
I have Laravel routes set up as the example below shows:
Route::group(array('domain' => 'example.com'), function()
{
Route::get('/', array('as' => 'root.index', 'uses' => '[email protected]'));
[...]
});
Route::group(array('domain' => 'api.example.com'), function()
{
Route::when('*', 'ApiFilter');
Route::get('/', array('as' => 'api.index', 'uses' => '[email protected]'));
[...]
});
Now, when it comes to responding to requests with errors (such as 404, 403, 500 etc) Laravel provides a great solution usingApp::error
and its related methods.
I would like to respond to errors differently depending on whether the request is for the root or api domain.
Can I do this usingApp::error
?
Hope that makes sense.
Thanks
Answer
Solution:
Yes, you can do this. Just need to get the request object from the
$exception
object in the exception handler, for example, if you have an exception handler like this:Now depending on the path you may take an action. You may use any public method of
Request
class, such asif($request->is('admin/*'))
or$request->url()
to get full url with domain.Answer
Solution:
You could also use content negotiation (
Accept
request header or URLs suffixed by.json
/.xml
) for different error formatting, like so:This would result in errors being returned as JSON, if request header
Accept
would not containtext/html
.So.. if you would go to api.yoursite.com with your browser - you would still see the default HTML error page with stack-trace and full details, because browser will send
Accept: text/html
.Otherwise, if
Accept
header is not set or does not explicitly containtext/html
- error will be formatted as JSON.Alternatively, instead of
preg_match
you could useRequest::wantsJson()
for detecting requested content format.Or if you absolutely need/want to separate API logics and go via sub-domain route..:
Answer
Solution:
I would apply separate filters to each route group, then specify error handling events in each filter.