How would you handle different error responses for different routes using Laravel

I have Laravel routes as shown below:

Route::group(array('domain' => 'example.com'), function()
{
    Route::get('/', array('as' => 'root.index', 'uses' => 'RootController@Index'));
    [...]
});

Route::group(array('domain' => 'api.example.com'), function()
{
    Route::when('*', 'ApiFilter');
    Route::get('/', array('as' => 'api.index', 'uses' => 'ApiController@Index'));
    [...]
});

Now, when it comes to answering queries with errors (e.g. 404, 403, 500, etc.), Laravel provides a great solution using its App::errorassociated 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 with help App::error?

Hope this makes sense.

thanks

+4
source share
3 answers

, . $exception , , , :

App::error(function(Exception $exception, $code)
{
    $request = $exception->getTrace()[0]['args'][0];
    $path = $request->path(); // will return path without domain, i.e. user/1
    // Take some action depending on the $path
});

. Request, if($request->is('admin/*')) $request->url(), URL- .

+1

(Accept URL-, .json/.xml) , :

App::error(function(Exception $exception, $code)
{
    if (!preg_match("@text/html@", Request::header('Accept')))
    {
        return Response::json
        (
            array("error" => array("message" => $exception->getMessage())),
            $code
        );
    }
});

JSON, Accept text/html.

, api.yoursite.com - HTML , Accept: text/html.

, Accept text/html - JSON.

preg_match Request::wantsJson() .

, / API ..:

App::error(function(Exception $exception, $code)
{
    if (preg_match("@^https?://api\.@", Request::url())) /* Or, if not using sub-domain: Request:is("api/*") */
    {
        return Response::json
        (
            array("error" => array("message" => $exception->getMessage())),
            $code
        );
    }
});
+1

I would apply separate filters to each group of routes, and then indicate error handling events in each filter.

0
source

Source: https://habr.com/ru/post/1525868/


All Articles