Created
September 15, 2012 14:18
-
-
Save awartoft/3728159 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** | |
* Handles errors during dispatch | |
* | |
* @param \Zend\Mvc\MvcEvent $e | |
*/ | |
public function onDispatchError(MvcEvent $e) | |
{ | |
$exception = $e->getParam('exception'); | |
// Not an exception causing this. | |
if (! $exception instanceof Exception) { | |
return; | |
} | |
// Check that we have a valid response | |
$response = $e->getResponse(); | |
// create a response object if we did not receive one | |
if (! $response) { | |
$response = new HttpResponse(); | |
$e->setResponse($response); | |
} | |
// Get the response code | |
$code = ($exception->getCode() == null) ? 500 : $exception->getCode(); | |
// Uhoh we should log this shieet | |
if ($exception instanceof LogicException) { | |
/** | |
* @var $logger \Zend\Log\Logger | |
*/ | |
$logger = $e->getApplication()->getServiceManager()->get('logger'); | |
$extras = array( | |
'ip' => $_SERVER['REMOTE_ADDR'], | |
'file' => $exception->getFile(), | |
'line' => $exception->getLine(), | |
); | |
$message = sprintf('Exception: %s with message: %s', get_class($exception), $exception->getMessage()); | |
// Log | |
$logger->err($message, $extras); | |
} | |
// respond with the correct code | |
$response->setStatusCode($code); | |
// render the error | |
$model = new ViewModel(); | |
// pass some variables | |
$model->setVariable('exception', $exception); | |
$model->setVariable('success', false); | |
// set the template (used in html requests) | |
$model->setTemplate('error/code/' . $code); | |
/** | |
* @var $view \Zend\View\View | |
*/ | |
$view = $e->getApplication()->getServiceManager()->get('viewManager')->getView(); | |
// Hook into the response | |
$view->getEventManager()->attach(ViewEvent::EVENT_RESPONSE, array($this, 'onRender'), 101); | |
// set the result | |
$e->setResult($model); | |
// doing this will stop all other exception handling strategies | |
$e->setError(null); | |
} | |
/** | |
* Lovely hack to keep our API consistent | |
* | |
* @param \Zend\View\ViewEvent $e | |
*/ | |
public function onRender(ViewEvent $e) | |
{ | |
if ($e->getRenderer() instanceof JsonRenderer) { | |
$response = json_decode($e->getResult()); | |
$e->setResult(json_encode($response->content)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment