From e8e067ea34bfae63d89bbc79118c8c9401f36f29 Mon Sep 17 00:00:00 2001 From: Johannes Meyer Date: Thu, 28 Nov 2019 15:14:49 +0100 Subject: [PATCH] MigrateController: Enhance error handling --- application/controllers/MigrateController.php | 34 ++++++++++++++++--- 1 file changed, 29 insertions(+), 5 deletions(-) diff --git a/application/controllers/MigrateController.php b/application/controllers/MigrateController.php index f7c521ad..d0e7cf6a 100644 --- a/application/controllers/MigrateController.php +++ b/application/controllers/MigrateController.php @@ -2,6 +2,8 @@ namespace Icinga\Module\Icingadb\Controllers; +use Exception; +use Icinga\Exception\IcingaException; use Icinga\Module\Icingadb\Compat\UrlMigrator; use Icinga\Module\Icingadb\Web\Controller; use ipl\Web\Url; @@ -15,22 +17,44 @@ class MigrateController extends Controller $this->httpBadRequest('No API request'); } - // TODO: Also verify content-type! + if ( + ! preg_match('/([^;]*);?/', $this->getRequest()->getHeader('Content-Type'), $matches) + || $matches[1] !== 'application/json' + ) { + $this->httpBadRequest('No JSON content'); + } $urls = $this->getRequest()->getPost(); $result = []; + $errors = []; foreach ($urls as $urlString) { $url = Url::fromPath($urlString); if (UrlMigrator::isSupportedUrl($url)) { - $urlString = UrlMigrator::transformUrl($url)->getAbsoluteUrl(); + try { + $urlString = UrlMigrator::transformUrl($url)->getAbsoluteUrl(); + } catch (Exception $e) { + $errors[$urlString] = [ + IcingaException::describe($e), + IcingaException::getConfidentialTraceAsString($e) + ]; + $urlString = false; + } } $result[] = $urlString; } - $this->getResponse()->json() - ->setSuccessData($result) - ->sendResponse(); + $response = $this->getResponse()->json(); + if (empty($errors)) { + $response->setSuccessData($result); + } else { + $response->setFailData([ + 'result' => $result, + 'errors' => $errors + ]); + } + + $response->sendResponse(); } }