krakphp / lava

Micro framework with massive potential
1 stars 0 forks source link

Better Error Handling #38

Closed ragboyjr closed 7 years ago

ragboyjr commented 7 years ago

Remove the wrap exceptions middleware and instead wrap every handler via the Link.

<?php

namespace Krak\Lava\Middleware;

use Krak\Mw;
use Krak\Http\Middleware\HttpLink;
use Krak\Lava;
use Psr\Log;
use Psr\Http\Message\ServerRequestInterface;

class LavaLink extends HttpLink implements Log\LoggerInterface
{
    use Log\LoggerTrait;

    public function __invoke(...$params) {
        try {
            return parent::__invoke(...$params);
        } catch (\Exception $e) {
            $this->debug('Wrapping caught exception into error');
            return $this->getApp()->renderError(Lava\Error::createFromException($e), $this->requestFromParams($params));
        } catch(\Throwable $e) {
            return $this->getApp()->renderError(Lava\Error::createFromException(new \Symfony\Component\Debug\Exception\FatalThrowableError($e)), $this->requestFromParams($params));
        }
    }

    public function getApp() {
        return $this->getContext()->getApp();
    }

    public function abort(...$args) {
        return $this->getApp()->abort(...$args);
    }

    public function log($level, $message, array $context = array()) {
        return $this->getApp()->log($level, $message, $context);
    }

    private function requestFromParams(array $params) {
        foreach ($params as $param) {
            if ($param instanceof ServerRequestInterface) {
                return $param;
            }
        }

        return $this->getApp()['request'];
    }
}