From 84044d5057cc4f8bc88f67461e6143be74c0e527 Mon Sep 17 00:00:00 2001 From: PJ Dietz Date: Wed, 21 Jan 2015 11:03:01 -0500 Subject: [PATCH] Re-add converting HttpExceptions to responses in Handler --- src/pjdietz/WellRESTed/Handler.php | 10 ++++++++-- test/HandlerTest.php | 21 +++++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/pjdietz/WellRESTed/Handler.php b/src/pjdietz/WellRESTed/Handler.php index 408c400..e941e63 100644 --- a/src/pjdietz/WellRESTed/Handler.php +++ b/src/pjdietz/WellRESTed/Handler.php @@ -4,12 +4,13 @@ * pjdietz\WellRESTed\Handler * * @author PJ Dietz - * @copyright Copyright 2014 by PJ Dietz + * @copyright Copyright 2015 by PJ Dietz * @license MIT */ namespace pjdietz\WellRESTed; +use pjdietz\WellRESTed\Exceptions\HttpExceptions\HttpException; use pjdietz\WellRESTed\Interfaces\HandlerInterface; use pjdietz\WellRESTed\Interfaces\RequestInterface; use pjdietz\WellRESTed\Interfaces\ResponseInterface; @@ -45,7 +46,12 @@ abstract class Handler implements HandlerInterface $this->request = $request; $this->args = $args; $this->response = new Response(); - $this->buildResponse(); + try { + $this->buildResponse(); + } catch (HttpException $e) { + $this->response->setStatusCode($e->getCode()); + $this->response->setBody($e->getMessage()); + } return $this->response; } diff --git a/test/HandlerTest.php b/test/HandlerTest.php index 5c55ba6..70da735 100644 --- a/test/HandlerTest.php +++ b/test/HandlerTest.php @@ -2,6 +2,7 @@ namespace pjdietz\WellRESTed\Test; +use pjdietz\WellRESTed\Exceptions\HttpExceptions\NotFoundException; use pjdietz\WellRESTed\Handler; class HandlerTest extends \PHPUnit_Framework_TestCase @@ -43,6 +44,18 @@ class HandlerTest extends \PHPUnit_Framework_TestCase ]; } + public function testTranslateHttpExceptionToResponse() + { + $mockRequest = $this->getMock('\pjdietz\WellRESTed\Interfaces\RequestInterface'); + $mockRequest->expects($this->any()) + ->method('getMethod') + ->will($this->returnValue("GET")); + + $handler = new ExceptionHandler(); + $resp = $handler->getResponse($mockRequest); + $this->assertEquals(404, $resp->getStatusCode()); + } + public function testReadAllowedMethods() { $mockRequest = $this->getMock('\pjdietz\WellRESTed\Interfaces\RequestInterface'); @@ -65,3 +78,11 @@ class OptionsHandler extends Handler return ["GET","POST"]; } } + +class ExceptionHandler extends Handler +{ + protected function get() + { + throw new NotFoundException(); + } +}