Skip to content

Instantly share code, notes, and snippets.

@gunnarlium
Last active September 20, 2018 12:47
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gunnarlium/8020641 to your computer and use it in GitHub Desktop.
Save gunnarlium/8020641 to your computer and use it in GitHub Desktop.
Exmple JsonErrorHandler for Silex (or any other app implementing HttpKernel)
<?php
// Register the error handler
$errorHandler = new JsonErrorHandler($app);
$app->error(array($errorHandler, 'handle'));
<?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 <gunnar@aptoma.com>
*/
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