获取 Laravel 发送的路由器输出

Get Laravel Router output sent

我在 API 中工作,有时它会中断并发送一些无效的数据 JSON。

我想检查每个请求的 return 值是否有效 JSON。

如何监听每个请求输出

可能在 Laravel\Lumen\Routing\RouterLaravel\Lumen\Application 上。

您可以注册一个在请求发送到服务器后运行的中间件,对吗?

例如:

<?php

namespace App\Http\Middleware;

use Closure;

class AfterMiddleware
{
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        // Perform validation action on $response? 

        return $response;
    }
}

正如@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);
    }
}

我正在使用 Lumen,然后我将其添加到 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";
    });
});