<?php

namespace Plainwork\Ui\Middleware;

use Plainwork\Http\Request;
use Plainwork\Ui\Component\Main;
use Plainwork\Ui\Ui;

class ExceptionMiddleware
{
    public $ui = Ui::class;

    public function __invoke(Request $request, callable $next)
    {
        try {
            $ret = $next($request);
        } catch (\Exception $e) {
            $ret = $e->getMessage();
            $ret = '__Error__' . ': ' . $ret;

            $ret = new Main($ret);
            $ret = $this->ui->render($ret, $request);
        }

        return $ret;
    }
}
