mirror of
https://github.com/shlinkio/shlink.git
synced 2026-03-11 09:43:13 +08:00
Created content based error handler which allows managing errors in a different way depending on the Accepted content type from the client
This commit is contained in:
39
module/Rest/src/Expressive/JsonErrorHandler.php
Normal file
39
module/Rest/src/Expressive/JsonErrorHandler.php
Normal file
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
namespace Shlinkio\Shlink\Rest\Expressive;
|
||||
|
||||
use Psr\Http\Message\RequestInterface as Request;
|
||||
use Psr\Http\Message\ResponseInterface as Response;
|
||||
use Shlinkio\Shlink\Common\Expressive\ErrorHandlerInterface;
|
||||
use Zend\Diactoros\Response\JsonResponse;
|
||||
|
||||
class JsonErrorHandler implements ErrorHandlerInterface
|
||||
{
|
||||
/**
|
||||
* Final handler for an application.
|
||||
*
|
||||
* @param Request $request
|
||||
* @param Response $response
|
||||
* @param null|mixed $err
|
||||
* @return Response
|
||||
*/
|
||||
public function __invoke(Request $request, Response $response, $err = null)
|
||||
{
|
||||
$status = $response->getStatusCode();
|
||||
$responsePhrase = $status < 400 ? 'Internal Server Error' : $response->getReasonPhrase();
|
||||
$status = $status < 400 ? 500 : $status;
|
||||
|
||||
return new JsonResponse([
|
||||
'error' => $this->responsePhraseToCode($responsePhrase),
|
||||
'message' => $responsePhrase,
|
||||
], $status);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $responsePhrase
|
||||
* @return string
|
||||
*/
|
||||
protected function responsePhraseToCode($responsePhrase)
|
||||
{
|
||||
return strtoupper(str_replace(' ', '_', $responsePhrase));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user