From d3dc17671597856e65d083ff9575d1b81916e224 Mon Sep 17 00:00:00 2001 From: Matjaz Prtenjak Date: Sun, 12 Dec 2021 16:49:21 +0100 Subject: [PATCH] Extend RestException to also accept error object This enables the developer to return additional data to user. So in case of an error in REST, the error can be additionaly explained { "error": { "code": 400, "message": "Missing properties", "data": { "severity": "high", "missing": [ 'date', 'name'] } } } --- source/Jacwright/RestServer/RestException.php | 10 +++++++++- source/Jacwright/RestServer/RestServer.php | 6 +++--- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/source/Jacwright/RestServer/RestException.php b/source/Jacwright/RestServer/RestException.php index 690acae..714e5f9 100644 --- a/source/Jacwright/RestServer/RestException.php +++ b/source/Jacwright/RestServer/RestException.php @@ -28,7 +28,15 @@ use Exception; class RestException extends Exception { - public function __construct($code, $message = null) { + private $_data = ''; + + public function __construct($code, $message = null, $data = null) { + $this->_data = $data; parent::__construct($message, $code); } + + public function getData() + { + return $this->_data; + } } diff --git a/source/Jacwright/RestServer/RestServer.php b/source/Jacwright/RestServer/RestServer.php index f5e1163..f023609 100755 --- a/source/Jacwright/RestServer/RestServer.php +++ b/source/Jacwright/RestServer/RestServer.php @@ -155,7 +155,7 @@ public function handle() { } } } catch (RestException $e) { - $this->handleError($e->getCode(), $e->getMessage()); + $this->handleError($e->getCode(), $e->getMessage(), $e->getData()); } } else { $this->handleError(404); @@ -196,7 +196,7 @@ public function addErrorClass($class) { $this->errorClasses[] = $class; } - public function handleError($statusCode, $errorMessage = null) { + public function handleError($statusCode, $errorMessage = null, $data = null) { $method = "handle$statusCode"; foreach ($this->errorClasses as $class) { @@ -220,7 +220,7 @@ public function handleError($statusCode, $errorMessage = null) { } $this->setStatus($statusCode); - $this->sendData(array('error' => array('code' => $statusCode, 'message' => $errorMessage))); + $this->sendData(array('error' => array('code' => $statusCode, 'message' => $errorMessage, 'data' => $data))); } protected function instantiateClass($obj) {