Как сказал @Mozammil, просто нужно промежуточное программное обеспечение для этого. Следи за тем, как это ощущается в финале.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Response;
use Mockery\Exception;
class AfterMiddleware
{
public function handle($request, Closure $next)
{
/** @var Response $response */
$response = $next($request);
// Response content are a JSON?
if (!$this->isJson($response->content())){
// Not a JSON!!
// Log everywhere
}
return $response;
}
private function isJson($string) {
json_decode($string);
return (json_last_error() == JSON_ERROR_NONE);
}
}
Я использую Люмен , затем я добавил его к bootstrap/app.php
:
$app->routeMiddleware([
'auth' => App\Http\Middleware\Authenticate::class,
'afterMiddleware' => App\Http\Middleware\AfterMiddleware::class
]);
И наконец добавил промежуточное ПО для моих api
маршрутов:
$router->group([
'middleware' => 'afterMiddleware',
'prefix' => 'api'
], function () use ($router) {
$router->get('/', function () use ($router) {
return response(["success"=>true]);
});
$router->get('/bug/', function () use ($router) {
return "I'm not a JSON and it will catch on AfterMiddleware handle";
});
});