Add HTTP Exceptions and convert to responses in Handler

This commit is contained in:
PJ Dietz 2014-07-10 22:47:05 -04:00
parent 25c423e0ee
commit 47fdc0e31b
3 changed files with 52 additions and 2 deletions

View File

@ -15,6 +15,7 @@
"php": ">=5.3.0"
},
"autoload": {
"psr-0": { "pjdietz\\WellRESTed": "src/" }
"psr-0": { "pjdietz\\WellRESTed": "src/" },
"classmap": ["src/pjdietz/WellRESTed/Exceptions/HttpExceptions.php"]
}
}

View File

@ -0,0 +1,39 @@
<?php
namespace pjdietz\WellRESTed\Exceptions;
class HttpException extends WellRESTedException
{
protected $code = 500;
protected $message = "500 Internal Server Error";
}
class BadRequest extends HttpException
{
protected $code = 400;
protected $message = "400 Bad Request";
}
class ForbiddenException extends HttpException
{
protected $code = 401;
protected $message = "401 Forbidden";
}
class UnautorizedException extends HttpException
{
protected $code = 403;
protected $message = "403 Unauthorized";
}
class NotFoundException extends HttpException
{
protected $code = 404;
protected $message = "404 Not Found";
}
class ConflictException extends HttpException
{
protected $code = 409;
protected $message = "409 Conflict";
}

View File

@ -10,6 +10,7 @@
namespace pjdietz\WellRESTed;
use pjdietz\WellRESTed\Exceptions\HttpException;
use pjdietz\WellRESTed\Interfaces\HandlerInterface;
use pjdietz\WellRESTed\Interfaces\ResponseInterface;
use pjdietz\WellRESTed\Interfaces\RequestInterface;
@ -43,7 +44,12 @@ abstract class Handler implements HandlerInterface
$this->request = $request;
$this->args = $args;
$this->response = new Response();
try {
$this->buildResponse();
} catch (HttpException $e) {
$this->response->setStatusCode($e->getCode());
$this->response->setBody($e->getMessage());
}
return $this->response;
}
@ -51,6 +57,10 @@ abstract class Handler implements HandlerInterface
* Prepare the Response. Override this method if your subclass needs to
* repond to any non-standard HTTP methods. Otherwise, override the
* get, post, put, etc. methods.
*
* An uncaught HttpException (or subclass) will be converted to a response
* using the exception's code as the status code and the exceptios message
* as the body.
*/
protected function buildResponse()
{