Last active
September 20, 2018 12:47
-
-
Save gunnarlium/8020641 to your computer and use it in GitHub Desktop.
Exmple JsonErrorHandler for Silex (or any other app implementing HttpKernel)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Register the error handler | |
$errorHandler = new JsonErrorHandler($app); | |
$app->error(array($errorHandler, 'handle')); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Aptoma; | |
use Silex\Application; | |
use Symfony\Component\HttpFoundation\Request; | |
use Symfony\Component\HttpKernel\Exception\HttpException; | |
/** | |
* JsonErrorHandler is able to capture exceptions and do smart stuff with them. | |
* | |
* The current implementation only formats the response as JSON if the request | |
* accepts JSON as content type. | |
* | |
* @author Gunnar Lium <[email protected]> | |
*/ | |
class JsonErrorHandler | |
{ | |
/** | |
* @var Application | |
*/ | |
private $app; | |
/** | |
* @var Request | |
*/ | |
private $request; | |
public function __construct(Application $app) | |
{ | |
$this->app = $app; | |
} | |
public function setRequest(Request $request) | |
{ | |
$this->request = $request; | |
return $this; | |
} | |
public function handle(HttpException $e, $code) | |
{ | |
if (!$this->request) { | |
try { | |
$this->request = $this->app['request']; | |
} catch (\RuntimeException $e) { | |
return null; | |
} | |
} | |
if (!in_array('application/json', $this->request->getAcceptableContentTypes())) { | |
return null; | |
} | |
$message = array( | |
'status' => $e->getStatusCode(), | |
'code' => $code, | |
'message' => $e->getMessage() | |
); | |
return $this->app->json( | |
$message, | |
$e->getStatusCode(), | |
$e->getHeaders() | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment