Added support for custom error handlers

This commit is contained in:
Phil 2014-12-31 21:06:06 +00:00
parent cf821c1614
commit cc17ebbe48
1 changed files with 30 additions and 0 deletions

View File

@ -23,6 +23,8 @@ class Router implements HandlerInterface
{ {
/** @var array Array of Route objects */ /** @var array Array of Route objects */
private $routes; private $routes;
/** @var array Array of Route objects for error handling. */
private $errorHandlers;
/** Create a new Router. */ /** Create a new Router. */
public function __construct() public function __construct()
@ -73,6 +75,29 @@ class Router implements HandlerInterface
} }
} }
/**
* Add a custom error handler.
*
* @param integer $error The error code.
* @param HandlerInterface $errorHandler The handler for the error.
*/
public function addErrorHandler($error, $errorHandler)
{
$this->errorHandlers[$error] = $errorHandler;
}
/**
* Add custom error handlers.
*
* @param array $errorHandlers An array mapping an integer error code to something implementing an HandlerInterface.
*/
public function addErrorHandlers(array $errorHandlers)
{
foreach ($errorHandlers as $error => $errorHandler) {
$this->addErrorHandler($error, $errorHandler);
}
}
/** /**
* Dispatch the singleton Request through the router and output the response. * Dispatch the singleton Request through the router and output the response.
* *
@ -85,6 +110,11 @@ class Router implements HandlerInterface
if (!$response) { if (!$response) {
$response = $this->getNoRouteResponse($request); $response = $this->getNoRouteResponse($request);
} }
$status = $response->getStatusCode();
if (array_key_exists($status, $this->errorHandlers)) {
$errorHandler = new $this->errorHandlers[$status]();
$response = $errorHandler->getResponse($request, $args);
}
$response->respond(); $response->respond();
} }