Created middleware to catch rest errors and return JSON responses

This commit is contained in:
Alejandro Celaya 2016-07-26 09:54:13 +02:00
parent 57d81115de
commit 0ef1e416c6
4 changed files with 70 additions and 6 deletions

View File

@ -26,11 +26,5 @@ return [
],
'priority' => 1,
],
'error' => [
'middleware' => [],
'error' => true,
'priority' => -10000,
],
],
];

View File

@ -12,5 +12,14 @@ return [
],
'priority' => 5,
],
'rest-error' => [
'path' => '/rest',
'middleware' => [
Middleware\Error\ResponseTypeMiddleware::class,
],
'error' => true,
'priority' => -10000,
],
],
];

View File

@ -19,6 +19,8 @@ return [
Middleware\CrossDomainMiddleware::class => InvokableFactory::class,
Middleware\CheckAuthenticationMiddleware::class => AnnotatedFactory::class,
Middleware\Error\ResponseTypeMiddleware::class => AnnotatedFactory::class,
],
],

View File

@ -0,0 +1,59 @@
<?php
namespace Shlinkio\Shlink\Rest\Middleware\Error;
use Acelaya\ZsmAnnotatedServices\Annotation\Inject;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Shlinkio\Shlink\Rest\Util\RestUtils;
use Zend\Diactoros\Response\JsonResponse;
use Zend\I18n\Translator\TranslatorInterface;
use Zend\Stratigility\ErrorMiddlewareInterface;
class ResponseTypeMiddleware implements ErrorMiddlewareInterface
{
/**
* @var TranslatorInterface
*/
private $translator;
/**
* ResponseTypeMiddleware constructor.
* @param TranslatorInterface $translator
*
* @Inject({"translator"})
*/
public function __construct(TranslatorInterface $translator)
{
$this->translator = $translator;
}
/**
* Process an incoming error, along with associated request and response.
*
* Accepts an error, a server-side request, and a response instance, and
* does something with them; if further processing can be done, it can
* delegate to `$out`.
*
* @see MiddlewareInterface
* @param mixed $error
* @param Request $request
* @param Response $response
* @param null|callable $out
* @return null|Response
*/
public function __invoke($error, Request $request, Response $response, callable $out = null)
{
$accept = $request->getHeader('Accept');
if (! empty(array_intersect(['application/json', 'text/json', 'application/x-json'], $accept))) {
$status = $response->getStatusCode();
$status = $status >= 400 ? $status : 500;
return new JsonResponse([
'error' => RestUtils::UNKNOWN_ERROR,
'message' => $this->translator->translate('Unknown error'),
], $status);
}
return $out($request, $response, $error);
}
}