/**
* Execute the middleware.
*
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @param callable $next
*
* @return ResponseInterface
*/
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
{
ob_start();
$level = ob_get_level();
$method = Run::EXCEPTION_HANDLER;
$whoops = $this->getWhoopsInstance($request);
$whoops->allowQuit(false);
$whoops->writeToOutput(false);
$whoops->sendHttpCode(false);
//Catch errors means register whoops globally
if ($this->catchErrors) {
$whoops->register();
}
try {
$response = $next($request, $response);
} catch (\Throwable $exception) {
$body = self::createStream($response->getBody());
$body->write($whoops->{$method}($exception));
$response = $response->withStatus(500)->withBody($body);
} catch (\Exception $exception) {
$body = self::createStream($response->getBody());
$body->write($whoops->{$method}($exception));
$response = $response->withStatus(500)->withBody($body);
} finally {
Utils\Helpers::getOutput($level);
}
if ($this->catchErrors) {
$whoops->unregister();
}
return $response;
}