On Sunday, April 9, 2017 at 12:26:41 PM UTC+2, Oscar Otero wrote:
>
>  This approach has some limitations:
> - There’s no (standard) way to decide whether the exception produces a 500 
> code, 404, 405, etc… This decision is made by the error handler.
> - There’s no way to get context data for loggin purposes.
>

I'd love to see both issues solved by some well known methods:

interface XResponseInterface extends ResponseInterface
{
    public function getAttributes();
    public function getAttribute($name, $default = null);
    public function withAttribute($name, $value);
    public function withoutAttribute($name);

}

Those are badly needed anyway.

class ErrorHandler implements MiddlewareInterface
{
    public function process(ServerRequestInterface $request, 
DelegateInterface $delegate)
    {
        try {
            $response = $delegate->process($request);
        } catch (Exception $exception) {
            // Generic error 500
            $response = $this
                ->factory
                ->createResponse(500)
                ->withAttribute(Exception::class, $exception);
 
           $response->getBody()->write('Server error');
        }

        if ($exception = $response->getAttribute(Exception::class)) {
            // Logs exceptions of inner middlewares too!
            $this->logger->error('Exception', ['exception' => $exception]);
        }

        return $response;
    }
}

Middlewares are already responsible for status codes, e.g.:

class SendFileMiddleware implements MiddlewareInterface
{
    public function process(ServerRequestInterface $request, 
DelegateInterface $delegate = null)
    {
        // …
        if (!file_exists($path)) {
            return $this
                ->factory
                ->createResponse(404)
                ->withAttribute(Exception::class, new Exception("The file 
\"$path\" does not exist."))
                ->…;
        }
        // …
    }

}

Nevertheless, a standardized HttpErrorException might be useful, but with 
slightly different semantics, e.g. on the client side:

try {
    $gget = new GuzzleGet(['base_uri' => 'https://httpbin.org']);
    $response = $gget(new Request('GET', '/'));

    $response->getStatusCode(); // may return 500!

} catch (HttpErrorException $exception) {
    // a network failure or anything else prevented the request from 
completing
    $exception->getResponse(); // may return null!
}

-- 
You received this message because you are subscribed to the Google Groups "PHP 
Framework Interoperability Group" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to php-fig+unsubscr...@googlegroups.com.
To post to this group, send email to php-fig@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/php-fig/de824f59-01e9-40f6-8d95-ef3189619531%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to