Use custom exception on response

This commit is contained in:
Ivan Diaz 2018-11-22 16:00:40 -03:00
parent ace895a4a2
commit ca80e3ed1f
4 changed files with 14 additions and 11 deletions

View File

@ -19,7 +19,7 @@ abstract class Controller {
$this->validate();
$this->handler();
} catch (\Exception $exception) {
Response::respondError($exception->getMessage());
Response::respondError($exception->getMessage(), $exception);
return;
}
};

View File

@ -1,2 +1,2 @@
<?php
<?php
class RequestException extends Exception {}

View File

@ -1,28 +1,31 @@
<?php
class Response {
private static $response;
private static $responseException;
public static function respondError($errorMsg, $data = null) {
$response = array(
public static function respondError($errorMsg, $exception = null) {
self::$response = array(
'status' => 'fail',
'message' => $errorMsg,
'data' => $data
'data' => null
);
self::$responseException = $exception;
$app = \Slim\Slim::getInstance();
$app->response->headers->set('Content-Type', 'application/json');
$app->response->setBody(json_encode($response));
$app->response->setBody(json_encode(self::$response));
$app->response->finalize();
}
public static function respondSuccess($data = null) {
$response = array(
self::$response = array(
'status' => 'success',
'data' => $data
);
$app = \Slim\Slim::getInstance();
$app->response->headers->set('Content-Type', 'application/json');
$app->response->setBody(json_encode($response));
$app->response->setBody(json_encode(self::$response));
$app->response->finalize();
}

View File

@ -8,17 +8,17 @@ class ResponseTest extends TestCase {
public function testErrorResponseFormat() {
//Mock data
$mockErrorValue = 'MOCK_ERROR_VALUE';
$mockData = array('example' => true);
$mockException = array('example' => true);
$expectedArgument = json_encode(array(
'status' => 'fail',
'message' => $mockErrorValue,
'data' => $mockData
'data' => null
));
$responseInstance = \Slim\Slim::getInstance();
$responseInstance = $responseInstance->response;
//Execute Response
Response::respondError($mockErrorValue, $mockData);
Response::respondError($mockErrorValue, $mockException);
//Should have been called with expected format
$this->assertTrue($responseInstance->setBody->hasBeenCalledWithArgs($expectedArgument));