RestApi: fix response codes

fixes #1092
This commit is contained in:
Thomas Gelf 2017-08-22 16:47:57 +02:00
parent 2f2b898a01
commit 1815ef1521
2 changed files with 14 additions and 3 deletions

View File

@ -32,13 +32,14 @@ abstract class RequestHandler
$this->processApiRequest(); $this->processApiRequest();
} }
protected function sendJson($object) public function sendJson($object)
{ {
$this->response->setHeader('Content-Type', 'application/json', true); $this->response->setHeader('Content-Type', 'application/json', true);
$this->response->sendHeaders();
echo json_encode($object, JSON_PRETTY_PRINT) . "\n"; echo json_encode($object, JSON_PRETTY_PRINT) . "\n";
} }
protected function sendJsonError($error, $code = null) public function sendJsonError($error, $code = null)
{ {
$response = $this->response; $response = $this->response;
if ($code === null) { if ($code === null) {
@ -55,6 +56,7 @@ abstract class RequestHandler
$message = $error; $message = $error;
} }
$response->sendHeaders();
$this->sendJson((object) ['error' => $message]); $this->sendJson((object) ['error' => $message]);
} }

View File

@ -42,15 +42,24 @@ abstract class ObjectController extends ActionController
{ {
parent::init(); parent::init();
$this->eventuallyLoadObject();
if ($this->getRequest()->isApiRequest()) { if ($this->getRequest()->isApiRequest()) {
$handler = new IcingaObjectHandler($this->getRequest(), $this->getResponse(), $this->db()); $handler = new IcingaObjectHandler($this->getRequest(), $this->getResponse(), $this->db());
try {
$this->eventuallyLoadObject();
} catch (NotFoundError $e) {
// Silently ignore the error, the handler will complain
$handler->sendJsonError($e, 404);
// TODO: nice shutdown
exit;
}
$handler->setApi($this->api()); $handler->setApi($this->api());
if ($this->object) { if ($this->object) {
$handler->setObject($this->object); $handler->setObject($this->object);
} }
$handler->dispatch(); $handler->dispatch();
} else { } else {
$this->eventuallyLoadObject();
if ($this->getRequest()->getActionName() === 'add') { if ($this->getRequest()->getActionName() === 'add') {
$this->addSingleTab( $this->addSingleTab(
sprintf($this->translate('Add %s'), ucfirst($this->getType())), sprintf($this->translate('Add %s'), ucfirst($this->getType())),